Call Constructor Base after Code Execution

后端 未结 9 2011
攒了一身酷
攒了一身酷 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:23

    Another hack if you can get away with calling a static method.

    public class ClassA
    {
        public ClassA()
        {
            Debug.WriteLine("Call A Constructor");
        }
    }
    
    public class ClassB:ClassA
    {
        public ClassB():this(aMethod())
        {
        }
    
        private ClassB(object empty):base()
        {
            Debug.WriteLine("Class B Second Constructor");
        }
    
        private static object aMethod()
        {
            Debug.WriteLine("Run me First");
            return null;
        }
    }
    

提交回复
热议问题