1. 任何該 Type 的 static properties/methods/fields 第一次被存取時
2. 任何該 Type 的 non-static methods/properties/indexers/constructors 第一次被呼叫時
由 JIT Compiler 在呼叫點之前【植入】額外的程式碼來呼叫 Type Constructor.
CLR 保證:
1. Type Constructor 在每一個 AppDomain 只會被呼叫一次
2. Type Constructor 是 thread-safe 的
CLR 不保證:
1. Type Constructor 被呼叫的順序
若希望 CLR 執行 Type Constructor, 可參考下列程式碼
namespace ConsoleApplication1 {
class A {
static A() { Console.WriteLine("static A()"); }
}
class Program {
static void Main(string[] args) {
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(A).TypeHandle);
Console.ReadKey();
}
}
}
但請注意!!! CLR 絕對不會在同一個 AppDomain 裡呼叫同一個 TypeConstructor 兩次, 也不保證 TypeConstructor 之間的呼叫順序.因此上面那個 RunClassConstructor 若使用第二次的話是完全無作用的.
-----------------------------------------------------------------------------
對於這個 class
class Dummy {
private static Int32 val = 5;
}
表面上他並沒有宣告 type constructor,
但為了初始化 val,
C# Compiler 其實會偷偷的幫它產生一個 type constructor.
沒有留言:
張貼留言