【问题标题】:Why is parent's constructor getting called?为什么父的构造函数被调用?
【发布时间】:2012-06-02 18:01:28
【问题描述】:

我有一个抽象类示例。另一个泛型类 UsesExample 使用它作为一个约束,带有一个 new() 约束。后来,我为 Example 类创建了一个子类 ExampleChild,并将其与泛型类一起使用。但不知何故,当泛型类中的代码尝试创建新副本时,它调用的不是子类中的构造函数,而是父类中的构造函数。为什么会这样? 代码如下:

abstract class Example {

    public Example() {
        throw new NotImplementedException ("You must implement it in the subclass!");
    }

}

class ExampleChild : Example {

    public ExampleChild() {
        // here's the code that I want to be invoken
    }

}

class UsesExample<T> where T : Example, new() {

    public doStuff() {
        new T();
    }

}

class MainClass {

    public static void Main(string[] args) {

        UsesExample<ExampleChild> worker = new UsesExample<ExampleChild>();
        worker.doStuff();

    }

}

【问题讨论】:

    标签: c# generics inheritance constructor


    【解决方案1】:

    当你创建一个对象时,所有的构造函数都会被调用。首先,基类构造函数构造对象,以便初始化基成员。稍后调用层次结构中的其他构造函数。

    此初始化可能会调用静态函数,因此如果抽象基类事件没有数据成员,则调用它的构造函数是有意义的。

    【讨论】:

    • 你确定吗?我不是 100% 了解 C#,但通常调用 parent 的构造函数需要通过调用 super() 来明确(无论如何在 Java 中)
    • 他是对的,您可以查看我在回答中提供的链接(其中一个是 msdn)
    • @MK:没错。在 C# 中,总是调用父构造函数。如果不指定: this(): base()调用,会自动调用无参构造函数。
    • d'uh,当然调用了基类的default构造函数。在 Java 中也是如此。
    【解决方案2】:

    每当您创建派生类的新实例时,都会隐式调用基类的构造函数。在您的代码中,

    public ExampleChild() {
        // here's the code that I want to be invoked
    }
    

    真的变成了:

    public ExampleChild() : base() {
        // here's the code that I want to be invoked
    }
    

    由编译器。

    您可以阅读 Jon Skeet 关于 C# 构造函数的详细 blog 帖子。

    【讨论】:

      【解决方案3】:

      在派生类中,如果未使用 base 关键字显式调用基类构造函数,则隐式调用默认构造函数(如果有)。

      来自msdn 另外,你可以阅读here

      【讨论】:

      • 澄清一下,如果没有对基类的显式调用,并且它没有可访问的默认构造函数,那么代码将无法编译。
      猜你喜欢
      • 2011-09-07
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      • 2013-12-11
      • 2015-04-28
      • 1970-01-01
      相关资源
      最近更新 更多