且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我怎样才能从派生类调用基类的构造函数参数,如果派生类没有参数的构造函数?

更新时间:2023-02-15 15:27:53

这不是完全清楚你的问题是什么,但我的犯罪嫌疑人的你要么要添加的明确的参数的构造函数到你的子类:

It's not entirely clear what your question is, but I suspect you either want to add an explicit parameterless constructor to your child class:

// Parameterless child constructor calling parameterized base constructor
public Child() : base("foo", "bar") {
}

或同时添加参数和无参数之一:

or add both a parameterized and parameterless one:

public Child() {
}

public Child(string foo, string bar) : base(foo, bar) {
}

请注意,构造函数的的继承 - 所以仅仅因为一个基类有一个特定的构造函数的签名并不意味着你可以实例使用签名的类。子类必须提供它自己。

Note that constructors aren't inherited - so just because a base class has a particular constructor signature doesn't mean you can instantiate a class using that signature. The child class has to provide it itself.

任何编译器提供的参数的构造函数总是会调用基类的参数的构造函数。

Any compiler-provided parameterless constructor will always call the parameterless constructor of its base class.