为什么调用父级的构造函数?

问题描述 投票:0回答:3

我有一个抽象类示例。另一个泛型类 UsesExample 使用它作为约束,并带有 new() 约束。后来,我创建了一个示例类的子类,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
3个回答
9
投票

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

此初始化可能会调用静态函数,因此即使没有数据成员,调用抽象基类的构造函数也是有意义的。


8
投票

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

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# 构造函数的详细 博客 文章来了解更多信息。


2
投票

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

来自 msdn 另外,您可以阅读这里

© www.soinside.com 2019 - 2024. All rights reserved.