据我所知,在运行时,CLR 实现为具有不同参数化值类型的相同泛型类型创建不同的机器代码(或任何运行时表示),但共享引用类型的机器代码。这是有道理的,因为引用类型将占用相同的大小(引用的大小)。
我不明白的是,这如何与明确使用直接通过 typeof(T) 或 is T 等依赖于 T 类型的代码一起工作。例如,在类中:
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")
是假的。
我在这里假设机器代码对于编译的泛型类型是相同的,这当然可能是错误的。
最佳答案
使用引用类型为每个泛型实例化生成的 native 代码确实是相同的(将 System.__Canon
作为内部参数)但这并不意味着代码不应该访问原始代码类型参数。 native 代码可以通过辅助函数访问元数据并检索类型。
检查由这种方法生成的实际 native 代码会很有用,但从浏览 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.
关于c# - 使用 'typeof'和 'is'时,c#如何共享引用类型的泛型实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51059194/