【问题标题】:static generic fields in generic classes泛型类中的静态泛型字段
【发布时间】:2016-08-31 16:04:01
【问题描述】:

据我所知,当 C# 中第一次调用类型时,CLR 找到此类型并为此类型创建对象类型,其中包含类型对象指针、同步块索引器、静态字段、方法表(第 4 章中的更多信息'CLR via C#' 书)。好的,一些泛型类型具有静态泛型字段。我们为这些字段设置值

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();
    }
}

【问题讨论】:

    标签: c# .net clr


    【解决方案1】:

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

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

    因此在您的代码中将创建三种类型:GenericTypesClass&lt;string, string&gt;GenericTypesClass&lt;int, int&gt;GenericTypesClass&lt;Simple,Simple&gt;

    【讨论】:

      猜你喜欢
      • 2012-06-14
      • 2012-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      相关资源
      最近更新 更多