Virtual member call in a constructor

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

    The rules of C# are very different from that of Java and C++.

    When you are in the constructor for some object in C#, that object exists in a fully initialized (just not "constructed") form, as its fully derived type.

    namespace Demo
    {
        class A 
        {
          public A()
          {
            System.Console.WriteLine("This is a {0},", this.GetType());
          }
        }
    
        class B : A
        {      
        }
    
        // . . .
    
        B b = new B(); // Output: "This is a Demo.B"
    }
    

    This means that if you call a virtual function from the constructor of A, it will resolve to any override in B, if one is provided.

    Even if you intentionally set up A and B like this, fully understanding the behavior of the system, you could be in for a shock later. Say you called virtual functions in B's constructor, "knowing" they would be handled by B or A as appropriate. Then time passes, and someone else decides they need to define C, and override some of the virtual functions there. All of a sudden B's constructor ends up calling code in C, which could lead to quite surprising behavior.

    It is probably a good idea to avoid virtual functions in constructors anyway, since the rules are so different between C#, C++, and Java. Your programmers may not know what to expect!

提交回复
热议问题