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警告)。通常,这被视为不良做法。