什么是等效于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.