Constructor Parameters and Inheritance

后端 未结 4 1016
生来不讨喜
生来不讨喜 2020-12-09 08:35

New to OOP and I\'m confused by how derived-class constructors work when inheriting from a base class in C#.

First the base class:

class BaseClass
{
         


        
4条回答
  •  温柔的废话
    2020-12-09 09:32

    If you want to provide the opportunity for the derived class NOT to set the BaseString, then you need to provide a default constructor in the base class like this:

    public BaseClass()
    {
    
    }
    

    Now in the derived class, you can call the constructor with no arguments in the base class like this:

    public SubClass(string AnotherString)
         : base()
    {
        // base() => explicit call to default construct in the base class.
        // Do something else
    }
    

    This provides good software engineering practice: if you want to provide the opportunity not to set the base class's string, then do so in the base class. Other 'hacks' like passing null as an argument to the base constructor only serve to tinker with the base class's internals in ways that should not be done from subclasses.

提交回复
热议问题