Share via


静的コンストラクタ (C# プログラミング ガイド)

更新 : 2008 年 7 月

静的コンストラクタは、静的データを初期化したり、1 回限りの特定の処理を実行したりする際に使用されます。静的コンストラクタは、最初のインスタンスを作成する前、または静的メンバが参照される前に自動的に呼び出されます。

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 メソッドを呼び出すことができます。

  • 静的コンストラクタが例外をスローした場合、ランタイムがもう一度そのコンストラクタを呼び出すことはありません。その型は、プログラムが実行されているアプリケーション ドメインの有効期間にわたって、初期化されていない状態のまま残ります。

使用例

次の例の Bus クラスには、静的コンストラクタと 1 つの静的メンバ 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 月

静的コンストラクタの例外に関する箇条書き項目を追加

コンテンツ バグ修正