Why should Dispose() be non-virtual?

前端 未结 8 1228
情书的邮戳
情书的邮戳 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.

提交回复
热议问题