如何在托管C ++中处理IDisposable?
我正在尝试在托管C ++(.NET 2.0)中处理IDisposable对象(FileStream ^ fs)并收到错误消息
I'm trying to Dispose of an IDisposable object(FileStream^ fs) in managed C++ (.NET 2.0) and am getting the error
Dispose':不是'System :: IO :: FileStream
Dispose' : is not a member of 'System::IO::FileStream
它说我应该改为调用析构函数.会打电话
It says that I should invoke the destructor instead. Will calling
fs->~FileStream();
在FileStream对象上调用dispose方法吗?为什么我不能打电话给Dispose?
call the dispose method on the FileStream object? Why can't I call Dispose?
正确的模式是删除对象:
The correct pattern is to just delete the object:
delete fs;
这将转换为对Dispose()的调用.
This will be translated into a call to Dispose().
有关某些内容的详细信息,请参见这篇文章正在幕后进行.这种习惯用法的优点是它允许您编写:
See this post for some of the details of what is going on under the hood. The advantage of this idiom is that it allows you to write:
{
FileStream fs(...)
...
}
并正确调用Dispose方法...等效于C#中的using块.文件流对象仍然分配在托管堆上.
And have the Dispose method called correctly ... equivalent to a using block in C#. The file stream object is still allocated on the managed heap.