是否有一种方法在所有构造函数运行后立即自动调用特定方法? [英] Is there a way to automatically call a particular method immediately after all constructors have run?
问题描述
我希望能够在构造派生对象时自动调用特定的方法,但是我不知道该怎么做。以下代码进行了说明。另一个答案是推荐的OnLoad,但是我在Mac上为Unity使用,而我的平台似乎不支持OnLoad。有什么建议吗?
I want to be able to call a particular method automatically upon construction of a derived object, however I can't think how to do it. The following code illustrates. Another answer recommended OnLoad, but I am doing this for Unity on Mac and OnLoad doesn't appear to be supported by my platform. Any suggestions?
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
}
}
推荐答案
不幸的是,没有内置的方法可以执行您想要的操作(这是一项经常需要的功能)。
Unfortunately there's no built-in way to do what you want (it's a fairly-often-requested feature).
一个解决方法是实现工厂模式,在这种模式下,您无需直接调用构造函数来创建对象,而是实现静态方法来为您创建对象。例如:
One workaround is to implement a factory pattern, where you don't create objects by calling the constructor directly, but instead implement a static method to create them for you. For example:
public class MyClass
{
public MyClass()
{
// Don't call virtual methods here!
}
public virtual void Initialize()
{
// Do stuff -- but may be overridden by derived classes!
}
}
然后添加:
public static MyClass Create()
{
var result = new MyClass();
// Safe to call a virtual method here
result.Initialize();
// Now you can do any other post-constructor stuff
return result;
}
而不是
var test = new MyClass();
您可以做
var test = MyClass.Create();
这篇关于是否有一种方法在所有构造函数运行后立即自动调用特定方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!