Virtual member call in a constructor

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

    Just to add my thoughts. If you always initialize the private field when define it, this problem should be avoid. At least below code works like a charm:

    class Parent
    {
        public Parent()
        {
            DoSomething();
        }
        protected virtual void DoSomething()
        {
        }
    }
    
    class Child : Parent
    {
        private string foo = "HELLO";
        public Child() { /*Originally foo initialized here. Removed.*/ }
        protected override void DoSomething()
        {
            Console.WriteLine(foo.ToLower());
        }
    }
    

提交回复
热议问题