代码之家  ›  专栏  ›  技术社区  ›  Nick

当使用“typeof”和“is”时,如何共享引用类型的泛型实现?

  •  2
  • Nick  · 技术社区  · 6 年前

    据我所知,clr实现在运行时为具有不同参数化值类型的同一泛型类型创建不同的机器代码(或任何运行时表示),但为引用类型共享机器代码。这是有意义的,因为引用类型将占用相同的大小(引用的大小)。

    我不明白的是,如果代码显式地使用依赖于t类型的代码,那么它是如何通过type of(t)或ist来工作的。例如,在类中:

    class TestClass<T> 
    {
        public static bool TestAType(Object pObj) { return pObj is T; }
    }
    

    我不明白t=list和t=string的相同实现如何允许 TestClass<String>.TestAType("hello") 说实话 TestClass<List<int>>.TestAType("hello") 是假的。

    我在这里假设编译的泛型类型的机器代码是相同的,这当然可能是错误的。

    2 回复  |  直到 6 年前
        1
  •  1
  •   IS4    6 年前

    使用引用类型为每个泛型实例化生成的本机代码实际上是相同的(具有 System.__Canon 但这并不意味着代码不能访问原始类型参数。本机代码可以通过helper函数访问元数据并检索类型。

    检查由这种方法生成的实际本机代码是有用的,但是从浏览sscli来看 this 功能完成工作,根据其描述:

    // Given information about how to do a runtime lookup, generate the tree
    // for the runtime lookup.
    //
    // Run-time lookup is required if the enclosing method is shared between instantiations
    // and the token refers to formal type parameters whose instantiation is not known
    // at compile-time.