Recently saw some simple face test, found that there are a few things wrong ah.
1. In the following example
usingSystem; classA { PublicA () {printfields (); } Public Virtual voidPrintfields () {}}classb:a {intx=1; inty; PublicB () {y=-1; } Public Override voidPrintfields () {Console.WriteLine ("X={0},y={1}", x, y); }
}
What output is generated when you use new B () to create an instance of B?
The answers on the internet are: x=1,y=0; x= 1 y = 1
When you instantiate B, because the inherited relationship first implements the constructor of a, and the subclass overrides the Printfields function of the parent class, the final output is x=1,y=0. Note: Before executing printfields (), the constructor of B also
Not executed.
Breakpoint is hit at the Btest's constructor, at which point the value of y is 0.
After executing y=-1, this line of code, the program has been executed. There will be no output, so the answer on the web is wrong.
If you want to implement a relay output x=1,y=0 and then output x= 1 Y =-1, you only need to execute the Printfields function in the Btest constructor.
Conjecture: It may be that individual interviewers deliberately remove the printfields function inside the Btest constructor to test if you are answering.
The Pit of C # Classic interview questions