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

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

    In .NET, every object constructor in an object hierarchy will be called regardless if you call :base() or not.

    :base() is implicitly called if you don't explicitly call it.

    :base() can be used if you want to call a different contructor on a parent object rather than the default constructor.

    If you have code in the parent constructor that should not be called everytime, it may be better to move that code to it's own method that will need to be called explicitly after the object is constructed. Or, create a parameterized constructor on the parent object and use the parameter to determine if the code should be executed or not.

    For example:

    :base(true) - This executes your code.
    :base(false) - This does not execute your code.
    

提交回复
热议问题