Force base method call

后端 未结 13 1874
独厮守ぢ
独厮守ぢ 2020-12-11 00:15

Is there a construct in Java or C# that forces inheriting classes to call the base implementation? You can call super() or base() but is it possible to have it throw a comp

13条回答
  •  不知归路
    2020-12-11 00:38

    I use the following technique. Notice that the Hello() method is protected, so it can't be called from outside...

    public abstract class Animal
    {
        protected abstract void Hello();
    
        public void SayHello()
        {
            //Do some mandatory thing
            Console.WriteLine("something mandatory");
    
            Hello();
    
            Console.WriteLine();
        }
    }
    
    public class Dog : Animal
    {
        protected override void Hello()
        {
            Console.WriteLine("woof");
        }
    }
    
    public class Cat : Animal
    {
        protected override void Hello()
        {
            Console.WriteLine("meow");
        }
    }
    

    Example usage:

    static void Main(string[] args)
    {
        var animals = new List()
        {
            new Cat(),
            new Dog(),
            new Dog(),
            new Dog()
        };
    
        animals.ForEach(animal => animal.SayHello());
        Console.ReadKey();
    }
    

    Which produces:

提交回复
热议问题