如何在托管C ++中处理IDisposable? [英] How do you dispose of an IDisposable in Managed C++?

查看:77
本文介绍了如何在托管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.

这篇关于如何在托管C ++中处理IDisposable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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