How can I tell the inheriting class to not call its base class' parameter-less constructor?

前端 未结 7 2731
礼貌的吻别
礼貌的吻别 2021-02-19 23:32

I was surprised to find out that the parameter-less constructor of my base class is called any time I call any constructor in a derived class. I thought that is what

7条回答
  •  不要未来只要你来
    2021-02-20 00:28

    As others have pointed out, a derived instance must call call one of its base class' constructors.

    If you want to control the execution of a base class' initialization logic, remove its default constructor and replace it with something like this:

    public class Base {
        // Base has no default constructor
        public Base(bool initialize) {
            if (initialize) {
                // ... logic here 
            }
        }    
    }
    

    And the derived constructors look like this:

    // Derived1 executes the initialization logic
    public Derived1(): base(true) {}
    
    // Derived2 does not
    public Derived2(): base(false) {}
    

提交回复
热议问题