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

前端 未结 7 2714
礼貌的吻别
礼貌的吻别 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:35

    Your requirement to only need to call the constructor for some derived objects is not in line with the object-oriented principles. If it's a Person, then it needs to be constructed as such.

    If you need shared initialization for some objects, then you should consider creating an Initialize method or adding a parameterized constructor that will be called by the specific derived objects.

    The parameterized constructor approach feels a little awkward:

    public abstract class Person
    {
        protected Person()
        {
        }
    
        protected Person( bool initialize )
        {
            if (initialize)
            {
                Initialize();
            }
        }
    
        // ...
    }
    
    public class Customer : Person
    {
        public Customer(string firstName, string lastName)
        {
           // ...
        }
    }
    
    public class Employee : Person
    {
        public Customer(string firstName, string lastName) : base(true)
        {
           // ...
        }
    }
    

提交回复
热议问题