我希望能够在构建派生对象时自动调用特定的方法,但我无法考虑如何去做。以下代码说明。另一个答案建议OnLoad,但我这样做的Mac上的统一和OnLoad似乎不支持我的平台。有什么建议么?有没有办法在所有构造函数运行后立即自动调用特定的方法?
public class Parent {
public Parent()
{
// A. Stuff to do before child constructor code runs
DoThisAutomaticallyAfterConstruction();
}
public void DoThisAutomaticallyAfterConstruction()
{
// C. In this example, this will run after A, before B. I want it to run ABC
}
}
public class Child : Parent {
public Child() : base()
{
// B. Stuff to do here after parent constructor code runs
}
}
这是代码味道给我。基类不应该与派生类有关。另外,构造器应该设置对象的初始化状态。 – Jason
+1 @ jason - 我同意。 – JonH