如果派生类没有参数化构造函数,如何从派生类中调用基类的参数化构造函数?

Akk*_*007 3 c# oop inheritance

我有一个带有两个构造函数的基类:默认构造函数和参数化构造函数.另一个类继承自该基类,它只有一个默认的构造函数.如何从派生类中调用基类的参数化构造函数?

Jon*_*eet 8

目前还不完全清楚你的问题是什么,但我怀疑你要么在你的子类中添加一个显式的无参数构造函数:

// Parameterless child constructor calling parameterized base constructor
public Child() : base("foo", "bar") {
}
Run Code Online (Sandbox Code Playgroud)

或者添加参数化和无参数的:

public Child() {
}

public Child(string foo, string bar) : base(foo, bar) {
}
Run Code Online (Sandbox Code Playgroud)

请注意,构造函数不是继承的 - 因为基类具有特定的构造函数签名并不意味着您可以使用该签名实例化类.儿童班必须自己提供.

任何编译器提供的无参数构造函数将始终调用其基类的无参数构造函数.