Invoking constructor of derived class execute before constructor of base class

后端 未结 3 978
无人共我
无人共我 2021-01-03 04:20

Well, originally I had a couple of constants (like MAX_SPEED) with different values in every of the derived classes. The idea was to use those values in some methods of the

3条回答
  •  梦谈多话
    2021-01-03 05:08

    No, you can't do that. Base classes are always initialized first. However, you can do something like this:

    class BaseClass
    {
        public BaseClass()
        {
            this.Initialize();
        }
    
        protected virtual void Initialize()
        {
            System.Console.WriteLine("This should be shown after");
        }
    }
    
    class DerivedClass : BaseClass
    {
        public DerivedClass() : base()
        {
        }
    
        protected override void Initialize()
        {
            System.Console.WriteLine("This should be shown first");
            base.Initialize();
        }
    }
    

提交回复
热议问题