Virtual member call in a constructor

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

    Another interesting thing I found is that the ReSharper error can be 'satisfied' by doing something like below which is dumb to me. However, as mentioned by many earlier, it still is not a good idea to call virtual properties/methods in constructor.

    public class ConfigManager
    {
       public virtual int MyPropOne { get; private set; }
       public virtual string MyPropTwo { get; private set; }
    
       public ConfigManager()
       {
        Setup();
       }
    
       private void Setup()
       {
        MyPropOne = 1;
        MyPropTwo = "test";
       }
    }
    

提交回复
热议问题