Page 37 -
P. 37

이제 마지막 주제로 제네릭 타입 정의와 닫혀 있고 구성된 타입이 어떻게 다른지 알아보자. 이 둘
               은 타입이 초기화되는 방식과 타입별 상태가 처리되는 방식에 차이가 있다.




               2.1.7  제네릭 타입의 초기화와 상태


               typeof 연산자를 사용할 때 살펴본 것처럼 List<int>와 List<string>은 동일한 제네릭 타입을

               사용함에도 완전히 다른 타입으로 간주된다. 따라서 타입을 사용하는 방법뿐 아니라 타입을 초기
               화하고 정적 필드를 다루는 방법 또한 다르다. 닫혀 있고 구성된 타입은 개별적으로 초기화되고
               정적 필드도 독립적으로 가진다. 다음은 이를 보여주기 위해 간단히 구성한 카운터(스레드 안전하
               지 않은) 예제다.


                예제 2-8 제네릭 타입의 정적 필드 처리 ▶ GenericCounter.cs
                 class GenericCounter<T>
                 {
                     private static int value;    닫혀 있고 구성된 타입별로 하나씩 존재


                     static GenericCounter()
                     {
                         Console.WriteLine("Initializing counter for {0}", typeof(T));
                     }

                     public static void Increment()
                     {
                         value++;
                     }

                     public static void Display()
                     {
                         Console.WriteLine("Counter for {0}: {1}", typeof(T), value);
                     }
                 }


                 class GenericCounterDemo
                 {
                     static void Main()
                     {
                         GenericCounter<string>.Increment();    GenericCounter<string> 초기화 수행
                         GenericCounter<string>.Increment();


         078
   32   33   34   35   36   37   38   39