C#在构造函数中调用虚拟方法
示例
与C#中的C++不同,您可以从类构造函数中调用虚拟方法(好的,您也可以在C++中,但是起初的行为令人惊讶)。例如:
abstract class Base
{
protected Base()
{
_obj = CreateAnother();
}
protected virtual AnotherBase CreateAnother()
{
return new AnotherBase();
}
private readonly AnotherBase _obj;
}
sealed class Derived : Base
{
public Derived() { }
protected override AnotherBase CreateAnother()
{
return new AnotherDerived();
}
}
var test = new Derived();
//test._objisAnotherDerived如果您来自C++背景,这令人惊讶,基类构造函数已经可以看到派生类虚拟方法表!
注意:派生类可能尚未完全初始化(其构造函数将在基类构造函数之后执行),并且此技术很危险(对此也有StyleCop警告)。通常,这被视为不良做法。
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短