本文介绍了C#中带有Dispose()的终结器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请参阅MSDN中的代码示例:()
See the code sample from MSDN: (http://msdn.microsoft.com/en-us/library/b1yfkh5e(v=VS.100).aspx)
// Design pattern for a base class.
public class Base: IDisposable
{
private bool disposed = false;
//Implement IDisposable.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Free other state (managed objects).
}
// Free your own state (unmanaged objects).
// Set large fields to null.
disposed = true;
}
}
// Use C# destructor syntax for finalization code.
~Base()
{
// Simply call Dispose(false).
Dispose (false);
}
}
在Dispose()实现中,它调用GC.SupressFinalize
In the Dispose() implementation it calls GC.SupressFinalize();, but provide a destructor to finalise the object.
在调用GC.SuppressFinalize()时为析构函数提供实现的意义是什么?
What is the point of providing an implementation for the destructor when GC.SuppressFinalize() is called?
只是有点混淆了意图是什么?
Just little bit confused what the intentions are?
推荐答案
有2个情况:
- 您的代码调用Dispose(首选),并且终结器被取消,从而消除了开销。
- 您的代码泄漏了对象,GC调用了终结器。
这篇关于C#中带有Dispose()的终结器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!