Do not call the virtual method (Do not call overridable methods in constructors) or callconstructors
The CLR says, do not call Virtual Methods in constructors because if the instantiated type overwrites the virtual method, the implementation of the derived type on the virtual method will be executed. However, initialization of all fields in the hierarchy has not been completed yet. Therefore, calling a virtual method will lead to unpredictable behavior. In the final analysis, this is because the actual type of the method is not selected when the virtual method is called until it is run.
In MSDN, we also provide detailed prompts and examples.
Https://msdn.microsoft.com/en-us/library/ms182331.aspx
Let's test it with our own hands. Create two classes, Perople class and Chinese class. Don't look at the results first. See the following two classes. When you think about instantiating Chinese, what is the output?
1 public class People 2 { 3 public People() 4 { 5 PeopleSayHello(); 6 } 7 8 public virtual void PeopleSayHello() 9 {10 Console.WriteLine("hello");11 }12 }
Public class Chinese: People {private bool HaveAbility {get; set;} public Chinese () {HaveAbility = true;} public override void PeopleSayHello () {Console. WriteLine (HaveAbility? "Yes": "no") + "");}}
Next let's take a look at the call and output results:
Is it the same as running results in your mind?
In fact, the reason has been clearly stated in the first sentence. More commonly, when the derived class is instantiated, if no base constructor is explicitly called, by default, the base class is constructed without parameters. Therefore, in this example, when instantiating Chinese, the base class is constructed without parameters.
The initialization sequence of the Instance constructor is also related. When creating an instance, first allocate memory for the data field, and then initialize the additional fields of the object, including pointer reference of the type object, at last, the constructor of the type is called to set the initial state of the object.