Call Constructor Base after Code Execution

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

    There's a hacky way of doing it using an instance variable initializer:

    using System;
    
    class ClassA
    {
        public ClassA()
        {
            Console.WriteLine("Initialization");
        }  
    }
    
    class ClassB : ClassA
    {
        private readonly int ignoreMe = BeforeBaseConstructorCall();
    
        public ClassB()
        {
        }
    
        private static int BeforeBaseConstructorCall()
        {
            Console.WriteLine("Before new");
            return 0; // We really don't care
        }
    }
    
    class Test
    {
        static void Main()
        {
            new ClassB();
        }    
    }
    

    The less hacky way of doing it is to rethink how you construct a ClassB to start with. Instead of having clients call the constructor directly, provide a static method for them to call:

    public static ClassB CreateInstance()
    {
        Console.WriteLine("Before initialization stuff");
        return new ClassB();
    }
    

提交回复
热议问题