正如您在下面的代码中看到的那样,在构造Child对象期间,在Init()之前调用DoStuff()方法.
我的情况是,我有很多子课.因此,在每个子节点的构造函数中的Init()之后直接重复调用DoStuff()方法将不是一个优雅的解决方案.
有没有办法在父类中创建某种post构造函数,它将在子构造函数之后执行?这样,我可以在那里调用DoStuff()方法.
如果您有任何其他设计理念可以解决我的问题,我也想听听它!
abstract class Parent
{
public Parent()
{
DoStuff();
}
protected abstract void DoStuff();
}
class Child : Parent
{
public Child()
// DoStuff is called here before Init
// because of the preconstruction
{
Init();
}
private void Init()
{
// needs to be called before doing stuff
}
protected override void DoStuff()
{
// stuff
}
}
Run Code Online (Sandbox Code Playgroud)