Page 38 -
P. 38

GenericCounter<string>.Display();
                               GenericCounter<int>.Display();    GenericCounter<int> 초기화 수행
                               GenericCounter<int>.Increment();                                       2
                               GenericCounter<int>.Display();
                           }                                                                          C# 2
                       }


                    예제 2-8의 결과는 다음과 같다.


                       Initializing counter for System.String
                       Counter for System.String: 2
                       Initializing counter for System.Int32
                       Counter for System.Int32: 0
                       Counter for System.Int32: 1


                    출력 결과에서 두 가지에 집중할 필요가 있다. 하나는 GenericCounter<string>의 값과 GenericCounter
                    <int>의 값은 독립적이라는 점이고, 다른 하나는 정적 생성자는 닫혀 있고 구성된 타입별로 각기
                    호출되므로 두 번 호출된다는 점이다. 정적 생성자가 없다면, 각 타입의 초기화 타이밍을 보장할
                    수는 없지만 본질적으로 GenericCounter<string>과 GenericCounter<int>는 상호 독립된 타입으

                    로 간주할 수 있다.
                    좀 더 복잡한 경우를 살펴보자. 제네릭 타입은 다른 제네릭 타입을 중첩된 형태로 가질 수 있다.
                    이 경우 타입 인수를 어떻게 조합하느냐에 따라 각기 독립된 타입이 생성된다. 다음 예를 보자.


                       class Outer<TOuter>
                       {
                           class Inner<TInner>
                           {
                               static int value;
                           }
                       }

                    타입 인수로 int와 string을 사용한다고 할 때, 다음과 같이 독립적인 네 개의 타입이 생성될 수
                    있으며 그 각각은 고유의 value 필드를 가진다.


                       ●   Outer<string>.Inner<string>
                       ●   Outer<string>.Inner<int>

                       ●   Outer<int>.Inner<string>

                       ●   Outer<int>.Inner<int>
                                                                                                  079
   33   34   35   36   37   38   39