What's the point of overriding Dispose(bool disposing) in .NET?

后端 未结 8 986
故里飘歌
故里飘歌 2021-01-30 10:38

If I write a class in C# that implements IDisposable, why isn\'t is sufficient for me to simply implement

public void Dispose(){ ... } 

to han

8条回答
  •  说谎
    说谎 (楼主)
    2021-01-30 11:28

    If a class implements IDisposable.Dispose() and a derived class needs to add additional logic, that class must expose some kind of Dispose method that the derived class can chain to. Since some classes may implement IDisposable.Dispose() without having a public Dispose() method, it's useful to have a virtual method which will be protected in all implementations of IDisposable regardless of whether they have a public Dispose method or not. In most cases, the bool argument isn't really meaningful but should be thought of as a dummy argument to make the protected virtual Dispose(bool) have a different signature from the may-be-or-maybe-not-public Dispose().

    Classes which doesn't use a protected virtual Dispose(bool) will require derived classes to handle their cleanup logic in a fashion which differs from the convention. Some languages like C++/CLI which are only equipped to extend IDisposable implementations which follow that convention may be unable to derive classes from non-standard implementations.

提交回复
热议问题