如果将方法标记Initialize
为虚拟方法,则意味着派生类可以自由地覆盖该方法,可能不会base.Initialize
在进程中调用。如果发生这种情况不合适,则不要将该方法标记为虚拟方法。
就您而言,听起来您只需要Initialize
在每个类中使用两个私有方法:
public class A
{
public A()
{
Initialize();
}
private void Initialize()
{
}
}
public class B : A
{
public B()
{
Initialize();
}
private void Initialize()
{
}
}
或者,您可能想看看模板方法设计模式。你可以这样设计你的类:
public class A
{
public A()
{
Initialize();
}
private void Initialize()
{
// Initialize the base class A.
// Then call DerivedInitialize. If this is actually a derived object,
// DerivedInitialize will initialize the derived instance. Otherwise,
// it won't do anything.
DerivedInitialize();
}
protected virtual void DerivedInitialize()
{
}
}
public class B : A
{
public B()
{
Initialize();
}
protected override void DerivedInitialize()
{
// Initialize B-specific stuff...
}
}