如何为对象拥有的 IDisposable
对象调用 Dispose()
方法?
public class MyClass
{
public MyClass()
{
log = new EventLog { Source = "MyLogSource", Log = "MyLog" };
FileStream stream = File.Open("MyFile.txt", FileMode.OpenOrCreate);
}
private readonly EventLog log;
private readonly FileStream stream;
// Other members, using the fields above
}
对于这个例子,我应该实现Finalize()
吗?如果我根本不实现它会有什么问题吗?
我的第一反应是MyClass
应该实现IDisposable
。但是在MSDN文章中的以下语句让我感到困惑:
只有在直接使用非托管资源时才实现IDisposable。 如果您的应用程序仅使用实现IDisposable的对象,请勿提供IDisposable实现。
这个说法错了吗?