Some time ago to find a job, to interview two questions about C # constructors, first look at the static constructor of the title below (the original question is not so, but similar, because you can not remember the appearance of the topic, the second question is also):
Class Base
{
static base ()
{
Console.WriteLine ("Static Base");
}
Public Base ()
{
Console.WriteLine ("Base");
}
What output is generated when you create an instance of base? I see, quite simple, I thought at that time: the constructor is a member of the class, the instantiation of nature is only to use the instance member, the static member Bird thing, what rotten topic. So write "Base". Write-write, and then there is a bit of doubt (for the incomplete recognition of the program I still like the Code verification), and then found that I was really wrong. When you go to the new instance of a class and you do call the static constructor (if it exists), what is the call, when it is declared (Base B = null;) or instantiated (b = new Base ();) called? I think it's time for a statement, And then he found out that he was wrong. It's a little verbose, everybody. MSDN View the official description of the static constructor: HTTP://MSDN.MICROSOFT.COM/ZH-CN/LIBRARY/K9X6W0HC (v=vs.80). aspx
The next question I have is what happens to the parent-child class invocation of this static constructor in the inheritance relationship? I dare not jump to conclusions, old fault.
Continue writing code to add a subclass
Class
child:base
{
static child ()
{
Console.WriteLine (' Static Child ');
}
Public Child ()
{
Console.WriteLine (' Child ');
}
}
This time I go to new a child object, the output is as follows:
I'll go. In contrast to the invocation order of the instance constructor, the order of invocation of all its constructors is: itself static constructor-> the parent class static constructor-> the parent class instance constructor-> itself instance constructor.
This thing seems to be not very practical, but in a class containing static members, there can be a lot of useful.