可能重複:
Why doesn't the CLR always call value type constructors類型的靜態構造函數調用
發現旁邊的代碼里氏的書(我已經簡化它一點點):
internal struct SomeValType
{
static SomeValType()
{
Console.WriteLine("This never gets displayed");
}
public Int32 X;
}
public sealed class Program
{
public static void Main()
{
SomeValType a = new SomeValType { X = 123 };
Console.WriteLine(a.X);
}
}
輸出:
無法理解,爲什麼在WriteLine
靜態構造函數調用NEVEL。看着ILDasm - 構造函數代碼和方法調用都存在。如果我將任何靜態變量添加到SomeValType
並在構造函數中初始化,然後WriteLine
調用正確。
有人可以解釋,請在這種情況下的行爲?謝謝。
我試着讓X靜態並在構造函數中賦值。這使得控制檯輸出按預期顯示。同樣的事情發生,如果我完全刪除X並投入在Main()中調用的靜態方法。也許不調用靜態構造函數,除非調用/訪問靜態方法或成員? – 2011-05-01 10:29:48