2016-08-31 5 views
0

C#에서 첫 번째 호출 유형이 발견되면 CLR은이 유형을 찾아서 유형 객체 포인터, 동기화 블록 인덱서, 정적 필드, 메소드 테이블을 포함하는이 유형의 객체 유형을 만듭니다 이가 그 후 다시제네릭 클래스의 정적 제네릭 필드

GenericTypesClass<string, string>.firstField = "firstField"; 
GenericTypesClass<string, string>.secondField = "secondField"; 

GenericTypesClass<int, int>.firstField = 1; 
GenericTypesClass<int, int>.secondField = 2; 

필드에 대한 (책 'C#을 통해 CLR'의 4 장에 대한 추가 정보를 원하시면) .Okay, 일부 제네릭 형식은 정적 일반적인 fields.We 설정 값이 힙은 두 개의 다른 객체 유형을 만들었는지, 아니면 만들지 않았습니까?

여기

더 examles :

일반적인 유형이 제 매개 변수로 값 유형으로 구성된다
class Simple 
{ 
} 

class GenericTypesClass<Type1,Type2> 
{ 
    public static Type1 firstField; 
    public static Type2 secondField; 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     //first call GenericTypesClass, create object-type 
     Type type = typeof (GenericTypesClass<,>); 

     //create new object-type GenericTypesClass<string, string> on heap 
     //object-type contains type-object pointer,sync-block indexer,static fields,methods table(from Jeffrey Richter : Clr Via C#(chapter 4)) 
     GenericTypesClass<string, string>.firstField = "firstField"; 
     GenericTypesClass<string, string>.secondField = "secondField"; 

     //Ok, this will create another object-type? 
     GenericTypesClass<int, int>.firstField = 1; 
     GenericTypesClass<int, int>.secondField = 2; 

     //and another object-type? 
     GenericTypesClass<Simple,Simple>.firstField = new Simple(); 
     GenericTypesClass<Simple, Simple>.secondField = new Simple(); 
    } 
} 

답변

2

는, 런타임에서의 적절한 위치에 치환 ​​제공된 파라미터 또는 파라미터들에 특화된 일반 타입을 만들어 MSIL. 특수한 제네릭 형식은 매개 변수 (from here)로 사용되는 고유 값 형식마다 한 번 만들어집니다.

달리 매개 변수화 된 제네릭 형식을 다르게 사용할 때마다 런타임에서 특수 형식의 새 버전을 생성합니다.이 형식은 힙에 저장되지만 확실하게 어딘가에 저장합니다.

은 그래서 코드에서 세 가지 유형이 생성됩니다 : GenericTypesClass<string, string>, GenericTypesClass<int, int>GenericTypesClass<Simple,Simple>

관련 문제