Call Constructor Base after Code Execution

后端 未结 9 2022
攒了一身酷
攒了一身酷 2021-02-12 12:33

Let say we have Class A and Class B. ClassB extends Class A. (ClassB : ClassA)

Now let\'s say that whenever I instantiate ClassB, I\'d like to Run some Random code and o

9条回答
  •  忘了有多久
    2021-02-12 13:35

    Another elegant solution would be to completely rethink how your objects are constructed. In the constructor of your base class you can call your own construct function, and you omit dependent future constructors, in the following way:

    public class ClassA
    {
        public ClassA()
        {
            Construct();
        }
    
        public virtual void Construct()
        {
            Console.WriteLine("3");
        }
    }
    
    public class ClassB : ClassA
    {
        public override void Construct()
        {
            Console.WriteLine("2");
            base.Construct();
        }
    }
    
    public class ClassC : ClassB
    {
        public override void Construct()
        {
            Console.WriteLine("1");
            base.Construct();
        }
    }
    

提交回复
热议问题