什么是等效于C#using语句的Managed C ++ [英] What is the Managed C++ equivalent to the C# using statement

查看:236
本文介绍了什么是等效于C#using语句的Managed C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在托管C ++中对以下C#代码进行编码

How would one code the following C# code in Managed C++

void Foo()
{
    using (SqlConnection con = new SqlConnection("connectionStringGoesHere"))
    {
         //do stuff
    }
}

澄清:
对于托管对象。

Clarificaton: For managed objects.

推荐答案

假设您的意思是C ++ / CLI(而不是旧的托管C ++),则可以选择以下选项:

Assuming you mean C++/CLI (not the old Managed C++), the following are your options:

(1)模仿使用-使用自动/基于堆栈的对象进行阻止:

(1) Mimic a using-Block with using automatic / stackbased objects:

{
  SqlConnection conn(connectionString);
}

这将在下一个封闭块时调用 conn对象的析构函数结束。无论是封闭功能,还是手动添加以限制作用域的块都无所谓。

This will call the Destructor of the "conn" Object when the next enclosing block ends. Whether this is the enclosing function, or a block you manually add to limit scope doesn't matter.

(2)显式调用 Dispose,即破坏对象:

(2) Explicitly call "Dispose", i.e. destruct the object:

SqlConnection^ conn = nullptr;
try
{
  conn = gcnew SqlConnection(conntectionString);

}
finally
{
  if (conn != nullptr)
    delete conn;
}

第一个是使用的直接替代。第二个选项是一个选项,通常除非您有选择地将引用传递到其他地方,否则您将不需要这样做。

The first one would be the direct replacement for "using". The second one is an option, typically you won't need to do unless you optionally pass the reference to somewhere else.

这篇关于什么是等效于C#using语句的Managed C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆