Max*_*kov 4 c# generics inheritance constructor
我有一个asbtract类的例子.另一个泛型类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();
}
}
Run Code Online (Sandbox Code Playgroud)
当您创建对象时,将调用所有构造函数.首先,基类构造函数构造对象,以便初始化基本成员.稍后调用层次结构中的其他构造函数.
此初始化可以调用静态函数,以便在没有数据成员的情况下调用抽象基类事件的构造函数是有意义的.
每当您创建派生类的新实例时,都会隐式调用基类的构造函数.在你的代码中,
public ExampleChild() {
// here's the code that I want to be invoked
}
Run Code Online (Sandbox Code Playgroud)
真的变成了:
public ExampleChild() : base() {
// here's the code that I want to be invoked
}
Run Code Online (Sandbox Code Playgroud)
由编译器.
您可以在Jon Skeet 关于C#构造函数的详细博客文章中阅读更多内容.
| 归档时间: |
|
| 查看次数: |
230 次 |
| 最近记录: |