Constructor Parameters and Inheritance

后端 未结 4 1002
生来不讨喜
生来不讨喜 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:35

    As to why you can't do:

    public SubClass(string SubString) : base(BaseString)
    

    What would BaseString be?

    You could do:

    public SubClass(string SubString) : base("SomeFixedString")
    

    or

    public SubClass(string SubString) : base(SubString)
    

    But if you want to pass one string to the base class constructor's parameter and have an additional one, you'll need to accept two parameters.

    As to keeping the same name, you don't. You could do:

    public SubClass(string AnotherString, string SubString) : base(AnotherString)
    

    As to the last question, the first parameter isn't doing nothing, it's being passed to the base class constructor. You could use it for something else if you wanted to.

提交回复
热议问题