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

时间:2011-02-28 12:31:41

标签: c# oop inheritance

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

3 个答案:

答案 0 :(得分:8)

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

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

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

public Child() {
}

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

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

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

答案 1 :(得分:2)

这样的东西?

class Parent
{
    public Parent(){}
    public Parent(string s) {}
}

class Child : Parent
{
    public Child() : base("42") { }
}

答案 2 :(得分:1)

你走了:

// 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   
        }
}
相关问题