1. 靜態構造函數用於初始化靜態數據,或用於執行僅需執行一次的特殊操作。
2. 靜態構造函數既沒有訪問修飾符,也沒有參數。
3. 在創建第一個實例或引用任何靜態成員之前,將自動調用靜態構造函數來初始化類。
4. 無法直接調用靜態構造函數。
5. 如果靜態構造函數引發異常,運行時將不會再次調用該構造函數,並且在程序運行所在的應用程序域的生存期內,類型將保持未初始化。
class Program
{
static void Main(string[] args)
{
// 在bus1實例化後調用靜態構造函數,只調用一次
Bus bus1 = new Bus(71);
Bus bus2 = new Bus(72);
bus1.Drive();
System.Threading.Thread.Sleep(3600);
bus2.Drive();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
public class Bus
{
protected static readonly DateTime globalStartTime;
protected int RouteNumber { get; set; }
static Bus ()
{
globalStartTime = DateTime.Now;
Console.WriteLine("static constructor sets global start time to {0}", globalStartTime.ToLongTimeString());
}
public Bus (int routeNum)
{
RouteNumber = routeNum;
Console.WriteLine("Bus #{0} is created", RouteNumber);
}
public void Drive()
{
TimeSpan elapsedTime = DateTime.Now - globalStartTime;
Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}", this.RouteNumber, elapsedTime.TotalMilliseconds, globalStartTime.ToLongTimeString());
}
}