C# How to execute code after object construction (postconstruction)

后端 未结 9 1947
自闭症患者
自闭症患者 2020-12-18 17:32

As you can see in the code below, the DoStuff() method is getting called before the Init() one during the construction of a Child object.

I\'m in a situation where I

9条回答
  •  情深已故
    2020-12-18 18:17

    If you have a complex logic for constructing your objects then consider FactoryMethod pattern.

    In your case I would implement it as a simple

    public static Parent Construct(someParam)
    

    method that takes some parameter and based on it decides which child class to instantiate. You can remove your DoStuff() method call from the constructor and call it inside Construct() on the new instance.

    Also, you should avoid virtual/abstract method calls in the constructors. See this question for more details: Virtual member call in a constructor

提交回复
热议问题