简体   繁体   中英

How can I avoid that the inherited class have to pass the base class constructor parameter

I have a base classe and an inheriting child class.

The base classes constructor accepts a parameter which I do not want to pass from my child constructor.

The parameter is a generic List<MyInterface>

Is that possible with C#?

at the moment my child class constructor looks like this:

public ChildClass() : base (new List<MyInterface>());

Is there a better way without having to new up the List?

If your base class constructor expects a parameter you have to pass that parameter from Child class.

You have two options.

  1. Define a parameterless constructor in base class and then you can avoid passing your parameter. (Based on comment from @aevitas, if you are going to follow that approach, you may define the parameterless constructor as protected , as that will only be available to child classes)

Like:

public class BaseClass
{
   public BaseClass() // or protected
   {
     //does nothing
   }
}

and then call it like:

public ChildClass() : base ();

or just

public ChildClass() //Since base() would be called implicitly. 
  1. The other option is what you are using now, You can pass a new empty instance of your list or null as per your requirement.

You should also revisit your design. Not having a parameterless constructor in the base class implies that the class object requires that particular parameter to to work. Working around it is a code smell .

You could add a parameter-less constructor on your base class that creates the new List for you? Other than that, no, you have to do that.

You would have two constructors, like this:

public BaseClass(List<MyInterface> newList)
{
    //blah blah blah
}

public BaseClass()
{
    var myList = new List<MyInterface>();
}

Your base class must either

A) define a parameterless constructor so that you can invoke base() 

Or

B) be ok with accepting a null value for the List<MyInterface> param

Like everyone has said you either need a parameterless constuctor in the base class or you need to pass the parameter. If the parameter is not needed at all in the child class then that could be a code smell.

If you only want your child class to have access to a parameterless constructor and no other you could make it protected .

public class BaseClass {
    protected BaseClass() : this(new List<MyInterface>()) {
    }
    public BaseClass(List<MyInterface> newList)
    {
        //blah blah blah
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM