C#小知识之有趣的类型静态构造器
这是C#中一个有趣的现象,也许您从中可以窥见些许CLR在构造类型时的行为,以及JIT编译的触发式编译过程。
看下面一段代码:
classProgram { staticvoidMain() { myValueType1type1=newmyValueType1(); Console.WriteLine(myValueType1.myInt); Console.WriteLine("**********************"); myValueType2type2=newmyValueType2(); type2.myInt=23; Console.WriteLine(type2.myInt); Console.WriteLine("**********************"); myValueType3type3=newmyValueType3(); } }
structmyValueType1 { staticmyValueType1() { Console.WriteLine("HellofrommyValueType1"); //myInt=111; } publicstaticInt32myInt; }
structmyValueType2 { staticmyValueType2() { Console.WriteLine("HellofrommyValueType2"); } publicInt32myInt; }
structmyValueType3 { staticmyValueType3() { Console.WriteLine("HellofrommyValueType3"); myInt=333; } publicstaticInt32myInt; }