Visual Studio 2010 其他版本 此主題尚未評級 評價此主題
靜態建構函式用於初始化任何 靜態 資料,或用於執行僅需執行一次的特定操作。 在建立第一個執行個體或引用任何靜態成員之前,將自動調用靜態建構函式。
C#
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; }}
靜態建構函式具有以下特點:
靜態建構函式既沒有存取修飾詞,也沒有參數。
在建立第一個執行個體或引用任何靜態成員之前,將自動調用靜態建構函式來初始化類。
無法直接調用靜態建構函式。
在程式中,使用者無法控制何時執行靜態建構函式。
靜態建構函式的典型用途是:當類使用記錄檔時,將使用這種建構函式向記錄檔中寫入項。
靜態建構函式在為Unmanaged 程式碼建立封裝類時也很有用,此時該建構函式可以調用 LoadLibrary 方法。
如果靜態建構函式引發異常,運行時將不會再次調用該建構函式,並且在程式運行所在的應用程式定義域的生存期內,類型將保持未初始化。
樣本
在此樣本中,類 Bus 有一個靜態建構函式。 建立 Bus 的第一個執行個體(bus1)時,將調用該靜態建構函式來初始化該類。 輸出樣本驗證了即使建立 Bus 的兩個執行個體,該靜態建構函式也僅運行一次,並且在執行個體建構函式運行之前運行。
C#
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; // Property for the number of each bus. protected int RouteNumber { get; set; } // Static constructor to initialize the static variable. // It is invoked before the first instance constructor is run. static Bus() { globalStartTime = DateTime.Now; // The following statement produces the first line of output, // and the line occurs only once. Console.WriteLine("Static constructor sets global start time to {0}", globalStartTime.ToLongTimeString()); } // Instance constructor. public Bus(int routeNum) { RouteNumber = routeNum; Console.WriteLine("Bus #{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() { // The creation of this instance activates the static constructor. Bus bus1 = new Bus(71); // Create a second bus. Bus bus2 = new Bus(72); // Send bus1 on its way. bus1.Drive(); // Wait for bus2 to warm up. System.Threading.Thread.Sleep(25); // Send bus2 on its way. bus2.Drive(); // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } } /* Sample output: Static constructor sets global start time to 3:57:08 PM. Bus #71 is created. Bus #72 is created. 71 is starting its route 6.00 minutes after global start time 3:57 PM. 72 is starting its route 31.00 minutes after global start time 3:57 PM. */請參見
參考類和結構(C# 編程指南)建構函式(C# 編程指南)解構函式(C# 編程指南)概念C# 編程指南