Is there a way to automatically call a particular method immediately after all constructors have run?

前端 未结 4 1880
独厮守ぢ
独厮守ぢ 2021-02-12 12:54

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 a

4条回答
  •  甜味超标
    2021-02-12 13:36

    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!
      }
    }
    

    then add:

    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;
    }
    

    and instead of doing

    var test = new MyClass();
    

    you can do

    var test = MyClass.Create();
    

提交回复
热议问题