微软建议在派生类中提供protected virtual void Dispose(bool disposing)
来实现基类。我有一个较早的已有类,没有提供这样的函数。知道基类是可释放的,我们能否在任何派生类中简单地使用以下代码?
class Base : IDisposable
{
//This somehow disposes it's resources
}
class Derived : Base
{
bool disposed;
private void PrivateDispose(bool disposing)
{
if (disposed) return;
if (disposing) {
// Cleanup managed resources
// ...
// Simply dispose base class
base.Dispose();
}
// Cleanup unmanged resources if any
// ...
disposed = true;
}
public void Dispose()
{
PrivateDispose(true);
GC.SuppressFinalize(this);
}
// Only provide Finalizer if we have unmanaged resources
~Derived()
{
PrivateDispose(false);
}
}