鉴于我有以下类型
interface IMyInterface<T> { }
class MyClass<T> : IMyInterface<T> { }
为什么以下 5 行不会产生相同的结果?
var type1 = typeof(IMyInterface<>);
var type2 = typeof(IMyInterface<object>).GetGenericTypeDefinition();
var type3 = typeof(MyClass<>).GetInterfaces().Single();
var type4 = typeof(MyClass<object>).GetInterfaces().Single().GetGenericTypeDefinition();
var type5 = typeof(MyClass<object>).GetGenericTypeDefinition().GetInterfaces().Single();
type1, type2 & type4 相同
type3 和 type5 相同
最佳答案
对于3和5,是不同的类型;这是 IMyInterface<SpecificT>
其中 SpecificT
是来自 MyClass<T>
的通用类型参数(不是实际已知的值,而是参数本身) - 即它是相关的。
这不同于完全免费(独立)T
在IMyInterface<T>
,这是 1、2 和 4 提供的。
如果重命名 T,它会变得更加明显:
interface IMyInterface<TA> { }
class MyClass<TB> : IMyInterface<TB> { }
现在检查 .GetGenericArguments().Single().Name
针对每个。对于 1、2 和 4,它是 TA
.对于 3 和 5,它是 TB
.
关于c# - GetGenericTypeDefinition 返回不同的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23803939/