Avoid calling virtual methods in an instance constructor - whether it is direct or indirect (virtual method first in the constru

xiaoxiao2021-03-06  51

The conditions for problems here are "Calling the virtual method in the instance constructor", if the virtual method is called elsewhere, there is no problem. Look at the following code: use system;

Class base {public base () {console.write ("base construct loading! / n"); this.aa (); // Note that this is what we need to avoid}

Public virtual void aa () {console.write ("Base aa load! / n");

}

Class basechild: base {public basechild () {console.write ("basechild construct loading! / n");}

Public override void aa () {console.write ("Base Basechild Aa Load! / N");

}

}

Class class1 {

Static void main (string [] args) {basechild bc = new basechild (); console.read ();}} display result is: base construct loading! basechild Construct Load! Basechild Construct Load! Not constructed in Basechild At the time, the AA method rewritted in Basechild has been executed - this is the problem. "When an Object has not completed initialization, it makes it to exercise the behavior is not reasonable."

转载请注明原文地址:https://www.9cbs.com/read-64686.html

New Post(0)