Why should Dispose() be non-virtual?

前端 未结 8 1211
情书的邮戳
情书的邮戳 2020-12-15 03:12

I\'m new to C#, so apologies if this is an obvious question.

In the MSDN Dispose example, the Dispose method they define is non-virtual. Why is that? It seems odd

相关标签:
8条回答
  • 2020-12-15 04:08

    This is certainly not an obvious one. This pattern was especially choosen because it works well in the following scenario's:

    • Classes that don't have a finalizer.
    • Classes that do have a finalizer.
    • Classes that can be inheritted from.

    While a virtual Dispose() method will work in the scenario where classes don't need finalization, it doesn't work well in the scenario were you do need finalization, because those types often need two types of clean-up. Namely: managed cleanup and unmanaged cleanup. For this reason the Dispose(bool) method was introduced in the pattern. It prevents duplication of cleanup code (this point is missing from the other answers), because the Dispose() method will normally cleanup both managed and unmanaged resources, while the finalizer can only cleanup unmanaged resources.

    0 讨论(0)
  • 2020-12-15 04:11

    If the base class has resources that need to be cleaned up at Dispose() time, then having a virtual Dispose method that's overridden by an inheriting class prevents those resources from being released unless the inheriting class specifically calls the base's Dispose method. A better way would implement it would be to have each derived class implement IDisposable.

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