我知道,从基类的构造函数调用虚方法可能是危险的,因为子类可能不处于有效状态.(至少在C#中)
我的问题是如果虚拟方法是初始化对象状态的那个?它是很好的做法,还是应该是两个步骤,首先创建对象,然后加载状态?
第一个选项:(使用构造函数初始化状态)
public class BaseObject {
public BaseObject(XElement definition) {
this.LoadState(definition);
}
protected abstract LoadState(XElement definition);
}
Run Code Online (Sandbox Code Playgroud)
第二种选择:(使用两步法)
public class BaseObject {
public void LoadState(XElement definition) {
this.LoadStateCore(definition);
}
protected abstract LoadStateCore(XElement definition);
}
Run Code Online (Sandbox Code Playgroud)
在第一种方法中,代码的使用者可以使用一个语句创建和初始化对象:
// The base class will call the virtual method to load the state.
ChildObject o = new ChildObject(definition)
Run Code Online (Sandbox Code Playgroud)
在第二种方法中,消费者必须创建对象然后加载状态:
ChildObject o = new ChildObject();
o.LoadState(definition);
Run Code Online (Sandbox Code Playgroud)