Static Constructor(Type Constructor)
时间:2010-08-21 来源:RamondLee
there are two ways can make the Static Constructor be called.
1. if you want to initialize a instance of this type
2. if you want to access a static noninherited member of this type
please pay attention on the second one. Before this moment, I thought the static constructor would be called whenever you write code about this type. But it is not like that.
The following code demonstrate what I mean:
代码
{
static void Main(string[] args)
{
Console.WriteLine(Child.Value);
Console.ReadKey();
}
}
public class Base
{
public static int Value { get; set; }
}
public class Child:Base
{
static Child()
{
Console.WriteLine("type constructor");
}
}
the child's static constructor won't be called.
there are more details on book << CLR via C#>> charpter 8 Part 3.
And there is a program shows you how JIT treat different kinds of type constructors.
I changed the main method in this program to verify a truth about JIT compiler: the IL code only JIT-compiled once.

{
const Int32 iterations = 1000 * 1000 * 1000;
Console.WriteLine("type in 'ok' to continue:");
string a = Console.ReadLine();
while (a.Equals("ok"))
{
Console.WriteLine("type in 'ok' to excute the first method? ");
a = Console.ReadLine();
if (a.Equals("ok"))
PerfTest1(iterations);
PerfTest2(iterations);
Console.WriteLine("type in 'ok' to continue:");
a = Console.ReadLine();
}
Console.ReadKey();
}
if you replace the main method with this one, here is one possible output that you can get :
the key about this problem is the JIT will emit the different code based on the execute of type's static constructor, the perfTest1 and perfTest2 are actually have the same content, the only different here is that they did not get JIT-compiled at the same time. whichever method you execute first will make the second method run faster. you can see the output from PerfTest2 are always same(almost same), how many times the method had been called. Because the PerfTest2 method are the first method got called here, that make it run very solw just like the first time for ever.
What does that mean? It means that the native code will be cached after its first generated, there won't have any optimization for these codes in the future.