How to “properly” override a base class method?

前端 未结 4 1596
野性不改
野性不改 2020-12-25 10:59

Whenever i override a method of a base class, other than my implementation of this method, i seem to have 3 choices.

1) Call base.Method(), and then provide my imple

4条回答
  •  悲哀的现实
    2020-12-25 11:22

    This is why I feel virtual methods are dangerous when you ship them in a library. The truth is you never really know without looking at the base class, sometimes you have to fire up reflektor, read documentation or approach it with trial and error.

    When writing code myself I've always tired to follow the rule that says:

    Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called.

    This is taken from http://msdn.microsoft.com/en-us/library/ms229011.aspx, however this is for Event design though I believe I read this in the Framework Design Guidelines book (http://www.amazon.com/Framework-Design-Guidelines-Conventions-Libraries/dp/0321246756).

    However, this is obviously not true, ASP.NET web forms for example require a base call on Page_Load.

    So, long and short, it varies and unfortunately there is no instant way of knowing. If I'm in doubt I will omit the call initially.

提交回复
热议问题