如何在托管C++中编写以下C#代码:
void Foo()
{
using (SqlConnection con = new SqlConnection("connectionStringGoesHere"))
{
//do stuff
}
}
澄清: 针对托管对象。
如何在托管C++中编写以下C#代码:
void Foo()
{
using (SqlConnection con = new SqlConnection("connectionStringGoesHere"))
{
//do stuff
}
}
澄清: 针对托管对象。
假设您是指C++/CLI(而不是旧版Managed C++),以下是您的选择:
(1)使用自动/基于栈的对象来模拟using块:
{
SqlConnection conn(connectionString);
}
当下一个封闭块结束时,这将调用“conn”对象的析构函数。无论这是包含函数还是您手动添加以限制范围的块都无所谓。
(2) 显式调用“Dispose”,即销毁该对象:
SqlConnection^ conn = nullptr;
try
{
conn = gcnew SqlConnection(conntectionString);
}
finally
{
if (conn != nullptr)
delete conn;
}
第一个选项是“using”的直接替代。第二个选项是可选项,通常情况下您不需要这样做,除非您将参考文献选择传递到其他地方。void Foo(){
SqlConnection con("connectionStringGoesHere");
//do stuff
}
void foo()
{
using( Foo, p, gcnew Foo() )
{
p->x = 100;
}
}
with the following:
template <typename T>
public ref class using_auto_ptr
{
public:
using_auto_ptr(T ^p) : m_p(p),m_use(1) {}
~using_auto_ptr() { delete m_p; }
T^ operator -> () { return m_p; }
int m_use;
private:
T ^ m_p;
};
#define using(CLASS,VAR,ALLOC) \
for ( using_auto_ptr<CLASS> VAR(ALLOC); VAR.m_use; --VAR.m_use)
供参考:
public ref class Foo
{
public:
Foo() : x(0) {}
~Foo()
{
}
int x;
};
#include <iostream>
using namespace std;
class Disposable{
private:
int disposed=0;
public:
int notDisposed(){
return !disposed;
}
void doDispose(){
disposed = true;
dispose();
}
virtual void dispose(){}
};
class Connection : public Disposable {
private:
Connection *previous=nullptr;
public:
static Connection *instance;
Connection(){
previous=instance;
instance=this;
}
void dispose(){
delete instance;
instance = previous;
}
};
Connection *Connection::instance=nullptr;
#define using(obj) for(Disposable *__tmpPtr=obj;__tmpPtr->notDisposed();__tmpPtr->doDispose())
int Execute(const char* query){
if(Connection::instance == nullptr){
cout << "------- No Connection -------" << endl;
cout << query << endl;
cout << "------------------------------" << endl;
cout << endl;
return -1;//throw some Exception
}
cout << "------ Execution Result ------" << endl;
cout << query << endl;
cout << "------------------------------" << endl;
cout << endl;
return 0;
}
int main(int argc, const char * argv[]) {
using(new Connection())
{
Execute("SELECT King FROM goats");//out of the scope
}
Execute("SELECT * FROM goats");//in the scope
}
auto_handle
代替。#include <msclr/auto_handle.h>
void Foo()
{
msclr::auto_handle<MyDisposableType> myDisposable(CSharpClass::CreateDisposable());
myDispoable->DoStuff();
// myDisposable gets disposed here
}
如果您关心的是限制变量的生命周期而不是自动处理,您可以将其放入自己的作用域中:
void Foo()
{
{
SqlConnection con = new SqlConnection("connectionStringGoesHere");
// do stuff
// delete it before end of scope of course!
}
}
Dispose
函数。因此,如果您有一个“正确”实现了IDisposable
接口的类型,那么就应该没问题了。也就是说,实际的垃圾回收时间与Dispose
并没有什么关系,因为实际的清理是在代码中您期望的地方(“变量超出范围”的点)发生的(确定性)。 - Christian.K