构造函数和继承

时间:2014-09-27 19:52:53

标签: c#

我到处读到:

构造函数不会从基类继承到派生类

如果这是真的那么

当我们创建派生类的对象时,基类默认构造函数如何调用?

例如:

public class A
{
    public void AA()
    {
        //anything
    }
}

public class B : A
{
    public void BB()
    {
        //anything
    }
}

class Program
{  
    static void Main(string[] args)
    {

        B Bobject = new B(); // Why it will call class A's default constructor if constructors not inherit from base to derived class
    }
}

3 个答案:

答案 0 :(得分:1)

您可以查看C#编译器生成的IL。这是为B构造函数生成的:

B..ctor:
IL_0000:  ldarg.0     
IL_0001:  call        A..ctor
IL_0006:  nop         
IL_0007:  nop         
IL_0008:  nop         
IL_0009:  ret  

答案 1 :(得分:1)

将始终隐式调用基类的默认无参数构造函数。如果您的基类没有无参数构造函数,那么派生类必须调用该构造函数并提供必要的参数。

请参阅Will the base class constructor be automatically called?

所以回答你的问题不,基类的构造函数不会被继承,但是会被你的派生类构造函数调用,或者在你使用 new 关键字时隐式调用

答案 2 :(得分:0)

why

在您的示例B IS-A A中,它是A的扩展名。鉴于此,要构造BA位必须在B之前构建,否则B将无法访问并且由{0}}提供的功能A

是由Sergey Mozhaykin的答案提供的。

您可以通过向A添加非默认构造函数来证明这一点(从而删除默认的无参数构造函数),代码将无法编译,因为B不再知道如何构造A 1}}。