正如我所知道的,当第一次调用C#中的类型时,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;在那之后,堆上创建了两种不同的对象类型,还是没有?
这里有更多的例子:
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();
}
}发布于 2016-09-01 00:25:35
当第一次使用值类型作为参数构造泛型类型时,运行库将使用提供的一个或多个参数在MSIL中的适当位置替换一个或多个参数来创建专用的泛型类型。专门的泛型类型为用作参数的每个唯一值类型创建一次(from here)。
所以每次你使用不同的参数化泛型类型时,运行时都会创建一个新的专用版本,不确定它是否会将它存储在堆中,但它肯定会将它存储在某个地方。
因此,在您的代码中将创建三种类型:GenericTypesClass<string, string>、GenericTypesClass<int, int>和GenericTypesClass<Simple,Simple>
https://stackoverflow.com/questions/39254272
复制相似问题