基类不包含无参数构造函数?

soo*_*ise 50 c# constructor

我通过删除一些空构造函数使我的构造函数更严格一些.我对继承很新,并且对我得到的错误感到困惑:基类不包含无参数构造函数.如果没有A中的空构造函数,我怎么能从A继承A.另外,为了我个人的理解,为什么A2需要A的空构造函数?

Class A{
    //No empty constructor for A
    //Blah blah blah...
}

Class A2 : A{
    //The error appears here
}
Run Code Online (Sandbox Code Playgroud)

Pla*_*ure 89

在A2类中,您需要确保所有构造函数都使用参数调用基类构造函数.

否则,编译器将假定您要使用无参数基类构造函数来构造A2对象所基于的A对象.

例:

class A
{
    public A(int x, int y)
    {
        // do something
    }
}

class A2 : A
{
    public A2() : base(1, 5)
    {
        // do something
    }

    public A2(int x, int y) : base(x, y)
    {
        // do something
    }

    // This would not compile:
    public A2(int x, int y)
    {
        // the compiler will look for a constructor A(), which doesn't exist
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我以前从未见过这个,但这正是诀窍.非常感谢! (2认同)

Joe*_*Joe 8

例:

class A2 : A
{
   A2() : base(0)
   {
   }
}

class A
{
    A(int something)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)