Virtual member call in a constructor

后端 未结 18 1913
[愿得一人]
[愿得一人] 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条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 02:18

    The warning is a reminder that virtual members are likely to be overridden on derived class. In that case whatever the parent class did to a virtual member will be undone or changed by overriding child class. Look at the small example blow for clarity

    The parent class below attempts to set value to a virtual member on its constructor. And this will trigger Re-sharper warning, let see on code:

    public class Parent
    {
        public virtual object Obj{get;set;}
        public Parent()
        {
            // Re-sharper warning: this is open to change from 
            // inheriting class overriding virtual member
            this.Obj = new Object();
        }
    }
    

    The child class here overrides the parent property. If this property was not marked virtual the compiler would warn that the property hides property on the parent class and suggest that you add 'new' keyword if it is intentional.

    public class Child: Parent
    {
        public Child():base()
        {
            this.Obj = "Something";
        }
        public override object Obj{get;set;}
    }
    

    Finally the impact on use, the output of the example below abandons the initial value set by parent class constructor. And this is what Re-sharper attempts to to warn you, values set on the Parent class constructor are open to be overwritten by the child class constructor which is called right after the parent class constructor.

    public class Program
    {
        public static void Main()
        {
            var child = new Child();
            // anything that is done on parent virtual member is destroyed
            Console.WriteLine(child.Obj);
            // Output: "Something"
        }
    } 
    

提交回复
热议问题