Virtual member call in a constructor

后端 未结 18 1840
[愿得一人]
[愿得一人] 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:05

    I think that ignoring the warning might be legitimate if you want to give the child class the ability to set or override a property that the parent constructor will use right away:

    internal class Parent
    {
        public Parent()
        {
            Console.WriteLine("Parent ctor");
            Console.WriteLine(Something);
        }
    
        protected virtual string Something { get; } = "Parent";
    }
    
    internal class Child : Parent
    {
        public Child()
        {
            Console.WriteLine("Child ctor");
            Console.WriteLine(Something);
        }
    
        protected override string Something { get; } = "Child";
    }
    

    The risk here would be for the child class to set the property from its constructor in which case the change in the value would occur after the base class constructor has been called.

    My use case is that I want the child class to provide a specific value or a utility class such as a converter and I don't want to have to call an initialization method on the base.

    The output of the above when instantiating the child class is:

    Parent ctor
    Child
    Child ctor
    Child
    

提交回复
热议问题