Virtual member call in a constructor

后端 未结 18 1937
[愿得一人]
[愿得一人] 2020-11-22 01:27

I\'m getting a warning from ReSharper about a call to a virtual member from my objects constructor.

Why would this be something not to do?

18条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 01:56

    In order to answer your question, consider this question: what will the below code print out when the Child object is instantiated?

    class Parent
    {
        public Parent()
        {
            DoSomething();
        }
    
        protected virtual void DoSomething() 
        {
        }
    }
    
    class Child : Parent
    {
        private string foo;
    
        public Child() 
        { 
            foo = "HELLO"; 
        }
    
        protected override void DoSomething()
        {
            Console.WriteLine(foo.ToLower()); //NullReferenceException!?!
        }
    }
    

    The answer is that in fact a NullReferenceException will be thrown, because foo is null. An object's base constructor is called before its own constructor. By having a virtual call in an object's constructor you are introducing the possibility that inheriting objects will execute code before they have been fully initialized.

提交回复
热议问题