C# 泛型类中的静态泛型字段

C# 泛型类中的静态泛型字段,c#,.net,clr,C#,.net,Clr,正如我所知,当在C#中第一次调用类型时,CLR找到此类型并为此类型创建对象类型,该类型包含类型对象指针、同步块索引器、静态字段、方法表(有关详细信息,请参阅《CLR通过C#》一书的第4章)。好的,某些泛型类型具有静态泛型字段。我们为这些字段设置了值 GenericTypesClass<string, string>.firstField = "firstField"; GenericTypesClass<string, string>.secondField = "sec

正如我所知,当在C#中第一次调用类型时,CLR找到此类型并为此类型创建对象类型,该类型包含类型对象指针、同步块索引器、静态字段、方法表(有关详细信息,请参阅《CLR通过C#》一书的第4章)。好的,某些泛型类型具有静态泛型字段。我们为这些字段设置了值

GenericTypesClass<string, string>.firstField = "firstField";
GenericTypesClass<string, string>.secondField = "secondField";
GenericTypesClass.firstField=“firstField”;
GenericTypesClass.secondField=“secondField”;
再三

GenericTypesClass<int, int>.firstField = 1;
GenericTypesClass<int, int>.secondField = 2;
GenericTypesClass.firstField=1;
GenericTypesClass.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();
    }
}
简单类
{
}
类GenericTypesClass
{
公共静态类型1第一字段;
公共静态类型2第二字段;
}
班级计划
{
静态void Main(字符串[]参数)
{
//首先调用GenericTypesClass,创建对象类型
类型类型=类型(GenericTypesClass);
//在堆上创建新的对象类型GenericTypesClass
//对象类型包含类型对象指针、同步块索引器、静态字段、方法表(来自Jeffrey Richter:Clr Via C#(第4章))
GenericTypesClass.firstField=“firstField”;
GenericTypesClass.secondField=“secondField”;
//好的,这将创建另一个对象类型?
GenericTypesClass.firstField=1;
GenericTypesClass.secondField=2;
//还有另一种对象类型?
GenericTypesClass.firstField=新建简单();
GenericTypesClass.secondField=新建简单();
}
}

当泛型类型首先以值类型作为参数构造时,运行时将创建一个专用泛型类型,并在MSIL中的适当位置替换提供的一个或多个参数。为用作参数()的每个唯一值类型创建一次专用泛型类型

所以每次您使用不同的参数化泛型类型时,运行时都会创建一个新的泛型类型,并为其创建一个专门的版本,不确定它是否会将其存储在堆中,但它肯定会将其存储在某个地方


因此,在您的代码中,将创建三种类型:
GenericTypesClass
GenericTypesClass
GenericTypesClass

当泛型类型首次以值类型作为参数构造时,运行时创建一个专用泛型类型,并在MSIL中的适当位置替换提供的一个或多个参数。为用作参数()的每个唯一值类型创建一次专用泛型类型

所以每次您使用不同的参数化泛型类型时,运行时都会创建一个新的泛型类型,并为其创建一个专门的版本,不确定它是否会将其存储在堆中,但它肯定会将其存储在某个地方

因此,在代码中将创建三种类型:
GenericTypesClass
GenericTypesClass
GenericTypesClass