如何在托管C处理的IDisposable接口的++接口、如何在、IDisposable

2023-09-03 03:14:59 作者:思念不断轮回.

我想处置的IDisposable的对象(的FileStream ^ FS)的托管C ++(.NET 2.0),并正在错误

I'm trying to Dispose of an IDisposable object(FileStream^ fs) in managed C++ (.Net 2.0) and am getting the error

'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#。文件流对象仍然分配在托管堆中。

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.