Share via


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

静的コンストラクターは、静的データの初期化、または 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 クラスには静的コンストラクターがあります。 Bus の最初のインスタンスを作成すると (bus1)、クラスを初期化するために静的コンストラクターが呼び出されます。 Bus のインスタンスを 2 つ作成しても、静的コンストラクターは 1 回だけ、インスタンス コンストラクターの前に実行されることが、次のサンプル出力からわかります。

    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# プログラミング ガイド