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

后端 未结 8 985
故里飘歌
故里飘歌 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:27

    It's not strictly necessary. It is part of the recommended Disposable pattern. If you haven't read the Framework Design Guidelines section on this (9.3 in the first edition, don't have the second edition handy sorry) then you should. Try this link.

    It's useful for distinguishing between disposable cleanup and finalizable garbage-collection-is-trashing-me.

    You don't have to do it that way but you should read up on it and understand why this is recommended before discounting it as unnecessary.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题