How to “properly” override a base class method?

前端 未结 4 1598
野性不改
野性不改 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:36

    how could a child class know (without taking a look at base class implementation) which order (or option) is being expected by the parent class?

    There is no way to "know" this when you are subclassing and overriding a method. Proper documentation is really the only option here.

    Is there a way in which parent class could enforce one of the three alternates to all the deriving classes?

    The only option here is to avoid the issue. Instead of allowing the subclass to override the method, it can be declared non-virtual, and call a virtual method in the appropriate place. For example, if you want to enforce that subclasses "call your version first", you could do:

    public class BaseClass {
        public void Method() // Non-virtual
        {
              // Do required work
    
              // Call virtual method now...
              this.OnMethod();
        }
    
        protected virtual void OnMethod()
        { // Do nothing
        }
     }
    

    The subclasses can then "override" OnMethod, and provide functionality that happens after "method"'s work.

    The reason this is required is that virtual methods are designed to allow a subclass to completely replace the implementation of the parent class. This is done on purpose. If you want to prevent this, it's better to make the method non-virtual.

提交回复
热议问题