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

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

    In WPF applications, you can postpone the invokation of DoStuff() with the help of Dispatcher:

    abstract class Parent
    {
        public Parent()
        {
            Dispatcher.CurrentDispatcher.BeginInvoke(new Action(this.DoStuff));
        }
    
        private void DoStuff()
        {
            // stuff, could also be abstract or virtual
        }
    }
    

    However, it is not guaranteed that DoStuff() will be called immediately after the constructor.

提交回复
热议问题