2016-08-31 10 views
0

C#で最初にtypeを呼び出すとわかるように、CLRはこの型を見つけ、型オブジェクトポインタ、同期ブロックインデクサ、静的フィールド、メソッドテーブルを含むこの型のオブジェクト型を作成します(書籍「C#を経由でCLR」の第4章で詳細).Okay、いくつかの一般的なタイプは、このフィールドの静的ジェネリックfields.We設定値ジェネリッククラスの静的汎用フィールド

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

と再びその後

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

を持っていますヒープは2つの異なるオブジェクト型を作成したかどうかを確認します。ここ

より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)として使用される一意の値の種類ごとに1回作成されます。

異なるパラメータ化されたジェネリック型を使用するたびに、ランタイムはその特殊バージョンを新規作成します。これは、ヒープに格納するかどうかはわかりませんが、間違いなくどこかに格納します。 GenericTypesClass<string, string>GenericTypesClass<int, int>GenericTypesClass<Simple,Simple>

を:だからあなたのコード内の3種類が作成されます

関連する問題