Share via


static 陳述式

更新:2007 年 11 月

宣告類別宣告內部的新類別初始設定式。

 static identifier {    [body] }

引數

  • identifier
    必要項。類別名稱,包含初始設定式區塊。

  • body
    選擇項。程式碼,用來組成初始設定式區塊。

備註

類別物件第一次使用前,使用靜態初始設定式來初始化該物件 (非物件執行個體)。這個初始化只發生一次,而且它可以用來初始化類別中具有 static 修飾詞的初始設定式欄位。

類別可以包含數個使用靜態欄位宣告所散置的靜態初始設定式區塊。若要初始化類別,所有的靜態區塊和靜態欄位初始設定式是以它們出現在類別主體中的順序來執行。這個初始設定式是在第一次參考靜態欄位之前執行。

不要混淆 static 修飾詞和 static 陳述式。static 修飾詞代表一個屬於類別本身的成員,而非任何類別的執行個體。

範例

下列範例顯示一個簡單的類別宣告,其中靜態初始設定式是用來執行只需要做一次的計算。在這個範例中,階乘表只需要計算一次。需要階層時會從表格讀取。如果程式中需要多次使用大階乘,這種方法會比遞迴計算階乘快。

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 修飾詞