简体   繁体   中英

How to call parameterised base class constructor from parameterless derived class?

My base class does not contain a parameterless constructor.

So I can typically call the base class constructor like this:

public ItemFoldersForm(FormConstructor constuctorOptions): base(constuctorOptions.WindowTitle, constuctorOptions.TabName, constuctorOptions.TabButton)
      {

      }

All of that is pretty standard, but for ease of reuse I want to have a parameterless constructor in my derived class. This is because the constructor options are based on a random generator.

Something like this:

public ItemFoldersForm()
      {
         var constructorOptions = ConstructorOptions.GetRandomConstructorOptions();
         base: // what to do here....
      } 

Is this concept possible with c#?

You could define two constructors:

public ItemFoldersForm(FormConstructor constuctorOptions) : base(constuctorOptions.WindowTitle, constuctorOptions.TabName, constuctorOptions.TabButton)
{
}

public ItemFoldersForm() : this(ConstructorOptions.GetRandomConstructorOptions())
{
}

Use the default constructor to generate your random options, which are then passed to the overloaded constructor which passes on properties to the base.

Note that the only way to do this is before the body of the constructor.

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