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

后端 未结 9 1939
自闭症患者
自闭症患者 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:23

    How about this:

    abstract class Parent
    {
        public Parent()
        {
            Init();
            DoStuff();
        }
    
        protected abstract void DoStuff();
        protected abstract void Init();
    }
    
    class Child : Parent
    {
        public Child()
        {
        }
    
        protected override void Init()
        {
            // needs to be called before doing stuff
        }
    
        protected override void DoStuff() 
        {
            // stuff
        }
    }
    

提交回复
热议问题