Virtual member call in a constructor

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

    Reasons of the warning are already described, but how would you fix the warning? You have to seal either class or virtual member.

      class B
      {
        protected virtual void Foo() { }
      }
    
      class A : B
      {
        public A()
        {
          Foo(); // warning here
        }
      }
    

    You can seal class A:

      sealed class A : B
      {
        public A()
        {
          Foo(); // no warning
        }
      }
    

    Or you can seal method Foo:

      class A : B
      {
        public A()
        {
          Foo(); // no warning
        }
    
        protected sealed override void Foo()
        {
          base.Foo();
        }
      }
    

提交回复
热议问题