Does this keyword exist? When an overriding method needs to call the parent

前端 未结 3 1231
说谎
说谎 2021-01-12 20:46

Often, in C# documentation, you come across a member where the description says something along the lines of \"be sure to call the base method if you override this.\"

<
3条回答
  •  终归单人心
    2021-01-12 21:22

    You can't enforce it, but you can do it via a call like base.Foo(bar). base allows you to access members of the class you're inheriting from.

    You can kind of enforce this behavior by using the template method pattern. For example, imagine you had this code:

    abstract class Animal
    {
        public virtual void Speak()
        {
            Console.WriteLine("I'm an animal.");
        }
    }
    
    class Dog : Animal
    {
        public override void Speak()
        {
            base.Speak();
            Console.WriteLine("I'm a dog.");
        }
    }
    

    The trouble here is that any class inheriting from Animal needs to call base.Speak(); to ensure the base behavior is executed. You can automatically enforce this by taking the following (slightly different) approach:

    abstract class Animal
    {
        public void Speak()
        {
            Console.WriteLine("I'm an animal.");
            DoSpeak();
        }
    
        protected abstract void DoSpeak();
    }
    
    class Dog : Animal
    {
        protected override void DoSpeak()
        {
            Console.WriteLine("I'm a dog.");
        }
    }
    

    In this case, clients still only see the polymorphic Speak method, but the Animal.Speak behavior is guaranteed to execute. The problem is that if you have further inheritence (e.g. class Dachsund : Dog), you have to create yet another abstract method if you want Dog.Speak to be guaranteed to execute.

提交回复
热议问题