靜態建構函式 (C# 程式設計手冊)

更新: 2008 年 7 月

靜態建構函式可以用來初始化任何靜態資料,或執行只需執行一次的特定動作。在建立第一個執行個體或參考任何靜態成員之前,會自動呼叫靜態建構函式。

class SimpleClass
{
    // Static variable that must be initialized at run time.
    static readonly long baseline;

    // Static constructor is called at most one time, before any
    // instance constructor is invoked or member is accessed.
    static SimpleClass()
    {
        baseline = DateTime.Now.Ticks;
    }
}

靜態建構函式有下列屬性:

  • 靜態建構函式並不使用存取修飾詞,也沒有參數。

  • 在建立第一個執行個體或參考任何靜態成員之前,就會自動呼叫靜態建構函式以初始化類別

  • 不能直接呼叫靜態建構函式。

  • 使用者無法控制程式中靜態建構函式執行的時間。

  • 靜態建構函式通常用在當類別使用記錄檔,而建構函式被用來將項目寫入該檔案。

  • 當靜態建構函式可呼叫 LoadLibrary 方法時,也可以使用這種建構函式為 Unmanaged 程式碼建立包裝函式類別。

  • 如果靜態建構函式擲回例外狀況,執行階段將不會再一次叫用它,且在您的程式執行的應用程式定義域存留期中,型別都將保持未初始化狀態。

範例

在這個範例中,Bus 類別具有一個靜態建構函式和一個靜態成員 Drive()。當呼叫 Drive() 時,靜態建構函式會被叫用來初始化這個類別。

 public class Bus
 {
     // static variable used by all Bus instances
     // Represents the time the first bus of the day starts its route.
     protected static readonly DateTime globalStartTime;

     // Instance readonly variable
     protected int RouteNumber { get; set; }

     // Static constructor to initialize static variable.
     // It is invoked before the first instance constructor is called.
     static Bus()
     {
         globalStartTime = DateTime.Now;
         Console.WriteLine("Static ctor sets global start time to {0}", globalStartTime.ToLongTimeString());
     }

     // Instance constructor
     public Bus(int routeNum)
     {
         RouteNumber = routeNum;
         Console.WriteLine("{0} is created.", RouteNumber);
     }

     // Instance method.
     public void Drive()
     {
         TimeSpan elapsedTime = DateTime.Now - globalStartTime;

         // For demonstration purposes we treat milliseconds as minutes to 
         // simulate actual bus times. Do not do this in your actual bus schedule program!
         Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.",
                                 this.RouteNumber,
                                 elapsedTime.TotalMilliseconds,
                                 globalStartTime.ToShortTimeString());
     }
 }

 class TestBus
 {
     static void Main()
     {

         Bus bus = new Bus(71);
         bus.Drive();

         // Wait for next bus to warm up.
         System.Threading.Thread.Sleep(25);

         Bus bus2 = new Bus(72);
         bus2.Drive();


         // Keep the console window open in debug mode.
         System.Console.WriteLine("Press any key to exit.");
         System.Console.ReadKey();
     }
 }
 /* Output:
     Static ctor sets global start time to 10:04:08 AM
     71 is created.
     71 is starting its route 21.00 minutes after global start time 10:04 AM.
     72 is created.
     72 is starting its route 46.00 minutes after global start time 10:04 AM.      
*/


請參閱

概念

C# 程式設計手冊

參考

類別和結構 (C# 程式設計手冊)

建構函式 (C# 程式設計手冊)

解構函式 (C# 程式設計手冊)

變更記錄

日期

記錄

原因

2008 年 7 月

加入靜態建構函式中例外狀況的項目。

內容 Bug 修正。