我有几个问题我无法得到正确的答案。
1)当我们没有析构函数时,为什么要在 Dispose 函数中调用 SuppressFinalize 。
2) Dispose 和 finalize 用于在对象被垃圾回收之前释放资源。无论是托管资源还是非托管资源,我们都需要释放它,那么为什么我们需要在 dispose 函数中添加一个条件,当我们从 IDisposable:Dispose 调用这个被覆盖的函数时说 pass 'true' 并在从 finalize 调用时传递 false 。
请参阅我从网络复制的以下代码。
class Test : IDisposable
{
private bool isDisposed = false;
~Test()
{
Dispose(false);
}
protected void Dispose(bool disposing)
{
if (disposing)
{
// Code to dispose the managed resources of the class
}
// Code to dispose the un-managed resources of the class
isDisposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
如果我删除布尔受保护的 Dispose 函数并实现如下。
class Test : IDisposable
{
private bool isDisposed = false;
~Test()
{
Dispose();
}
public void Dispose()
{
// Code to dispose the managed resources of the class
// Code to dispose the un-managed resources of the class
isDisposed = true;
// Call this since we have a destructor . what if , if we don't have one
GC.SuppressFinalize(this);
}
}