Base class 不提供受保护的 Dispose(bool) 方法?

Base class that does not provide protected Dispose(bool) method?

MS 建议基础 class 应该在派生的 class 中提供 protected virtual void Dispose(bool disposing)。我有一个现有的 class 写得更早,它不提供这样的功能。通过知道事实库 class 是一次性的,我们可以在任何派生的 class 中简单地使用以下内容吗?

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);
    } 
}

是的,你可以。 MS 推荐这样做的原因是为了让派生类型的任何实现者都能轻松覆盖现有的 Dispose(bool disposing) 方法,因为 IDisposable 接口实现的 public void Dispose() 不是 virtual.

请注意,您应该使用此模式。变化:

private void PrivateDispose(bool disposing)

收件人:

protected virtual void Dispose(bool disposing)

因此,如果有人可能需要扩展您的 class,他可以简单地覆盖您的方法。

一般来说,here are some more guidelines for implementing IDisposable:

Dispose should meet the following conditions:

1) Be safely callable multiple times
2) Release any resources associated with the instance
3) Call the base class's Dispose method, if necessary
4) Suppress finalization of this class to help the GC by reducing the number of objects on the finalization queue.
5) Dispose shouldn't generally throw exceptions, except for very serious errors that are particularly unexpected (ie, OutOfMemoryException). Ideally, nothing should go wrong with your object by calling Dispose.