问题描述
我有两个构造函数的基类:一个默认的构造函数和一个参数的构造函数。另一类从基类继承,它只有一个默认的构造函数。我怎样才能调用基类的参数的构造函数从派生类?
I have a base class with two constructors: a default constructor and a parameterized constructor. Another class inherits from that base class and it only has a default constructor. How can I call the base class's parameterized constructor from the derived class?
推荐答案
这不是完全清楚你的问题是什么,但我的犯罪嫌疑人的你要么要添加的明确的参数的构造函数到你的子类:
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.
这篇关于我怎样才能从派生类调用基类的构造函数参数,如果派生类没有参数的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!