static ステートメント

クラス宣言の内部で新しいクラス初期化子を宣言します。

static identifier {
   [body]
}

引数

  • identifier
    必ず指定します。 初期化子ブロックを含むクラスの名前。

  • body
    省略可能です。 初期化子ブロックを構成するコード。

解説

static 初期化子は、使用する前の class オブジェクト (オブジェクト インスタンスではありません) を初期化します。 この初期化は一度だけ実行され、static 修飾子を持つクラスのフィールドを初期化するために使用できます。

static フィールド宣言を使用すると、複数の static 初期化子ブロックを、クラスのさまざまな場所に記述できます。 クラスを初期化するときには、すべての static ブロックと static フィールド初期化子が、クラス本体に記述されている順に実行されます。 この初期化は、static フィールドが最初に参照される前に実行されます。

static 修飾子と static ステートメントを混同しないでください。 static 修飾子は、メンバーがクラスのインスタンスではなく、クラス自身に属していることを示します。

使用例

static 初期化子を使用して、一度だけ実行する必要のある計算を実行する、簡単な class 宣言の例を次に示します。 この例では、階乗の表が一度だけ計算されています。 階乗が必要になった場合は、表から読み取ります。 プログラム中で大きな階乗が何度も必要になる場合は、繰り返し階乗を計算するよりも、この手法を使用する方が高速です。

static 修飾子は、階乗のメソッドに使用されています。

class CMath {
   // Dimension an array to store factorial values.
   // The static modifier is used in the next two lines.
   static const maxFactorial : int = 5;
   static const factorialArray : int[] = new int[maxFactorial];

   static CMath {
      // Initialize the array of factorial values.
      // Use factorialArray[x] = (x+1)!
      factorialArray[0] = 1;
      for(var i : int = 1; i< maxFactorial; i++) {
         factorialArray[i] = factorialArray[i-1] * (i+1);
      }
      // Show when the initializer is run.
      print("Initialized factorialArray.");
   }

   static function factorial(x : int) : int {
      // Should have code to check that x is in range.
      return factorialArray[x-1];
   }
};

print("Table of factorials:");

for(var x : int = 1; x <= CMath.maxFactorial; x++) {
   print( x + "! = " + CMath.factorial(x) );
}

このコードの出力は次のようになります。

Table of factorials:
Initialized factorialArray.
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120

必要条件

バージョン .NET

参照

参照

class ステートメント

static 修飾子