Why should Dispose() be non-virtual?

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

提交回复
热议问题