使用'typeof'和'is'时,c#如何共享引用类型的泛型实现?

How can c# share the generic implementations of reference types when 'typeof' and 'is' are used?

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

我不明白的是,这如何与明确使用直接通过 typeof(T) 或 is T 之类的代码依赖于 T 类型的代码一起工作。例如,在 class:

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") 为假。

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

为每个使用引用类型的泛型实例化生成的本机代码确实是相同的(具有 System.__Canon 作为内部参数)但这并不意味着代码不应该访问原始类型参数。本机代码可以通过辅助函数访问元数据并检索类型。

检查由这种方法生成的实际本机代码会很有用,但从浏览 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.