我有一个抽象类示例。另一个泛型类 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();
}
}
当你创建一个对象时,所有的构造函数都会被调用。首先,基类构造函数构造对象,以便初始化基类成员。随后调用层次结构中的其他构造函数。
此初始化可能会调用静态函数,因此即使没有数据成员,调用抽象基类的构造函数也是有意义的。
每当创建派生类的新实例时,都会隐式调用基类的构造函数。在你的代码中,
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# 构造函数的详细 博客 文章来了解更多信息。