我有一个基类,其中包含两个构造函数:默认构造函数和参数化构造函数。另一个类继承自该基类,并且只有一个默认构造函数。如何从派生类调用基类的参数化构造函数?
我有一个基类,其中包含两个构造函数:默认构造函数和参数化构造函数。另一个类继承自该基类,并且只有一个默认构造函数。如何从派生类调用基类的参数化构造函数?
不太清楚您的问题是什么,但我猜测您想要在子类中添加一个明确的无参构造函数:
// Parameterless child constructor calling parameterized base constructor
public Child() : base("foo", "bar") {
}
public Child() {
}
public Child(string foo, string bar) : base(foo, bar) {
}
class Parent
{
public Parent(){}
public Parent(string s) {}
}
class Child : Parent
{
public Child() : base("42") { }
}
给你:
// Parent class
class Parent
{
public Parent()
{
// Paremeterless constructor
}
public Parent(string a, int b)
{
// Paremterised constructor
}
}
// Child class
class Child : Parent
{
public Child()
:base("hi", 10)
{
// Parameterized constructor of the base class is invoked
}
}