static 문

클래스 선언 내부에서 새 클래스 이니셜라이저를 선언합니다.

static identifier {
   [body]
}

인수

  • identifier
    필수적 요소로서, 이니셜라이저 블록을 포함하는 클래스의 이름입니다.

  • body
    선택적 요소로서, 이니셜라이저 블록을 구성하는 코드입니다.

설명

static 이니셜라이저는 class 개체(개체 인스턴스가 아님)를 처음 사용하기 전에 초기화하는 데 사용됩니다. 이 초기화는 한 번만 발생하며 클래스에서 static 한정자가 있는 필드를 초기화하는 데 사용할 수 있습니다.

classstatic 필드 선언과 섞여 있는 여러 static 이니셜라이저 블록을 포함할 수 있습니다. class를 초기화하기 위해 모든 static 블록과 static 필드 이니셜라이저가 class 본문에 나타나는 순서대로 실행됩니다. 이 초기화는 static 필드를 처음 참조하기 전에 수행됩니다.

static 한정자를 static 문과 혼동하지 마십시오. static 한정자는 클래스의 인스턴스가 아니라 클래스 자체에 속하는 멤버를 나타냅니다.

예제

다음 예제에서는 한 번만 수행하면 되는 계산을 수행하기 위해 static 이니셜라이저가 사용되는 간단한 class 선언을 보여 줍니다. 이 예제에서는 계승 테이블을 한 번 계산합니다. 그런 다음 계승이 필요하면 해당 테이블에서 읽어 옵니다. 이 방법은 프로그램에서 큰 계승이 여러 번 필요한 경우에 재귀적으로 계승을 계산하는 것보다 더 빠릅니다.

static 한정자는 factorial 메서드에 사용됩니다.

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 한정자