c# - GetGenericTypeDefinition 返回不同的类型

标签 c# inheritance types type-systems

鉴于我有以下类型

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>通用类型参数(不是实际已知的,而是参数本身) - 即它是相关的。

这不同于完全免费(独立)TIMyInterface<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/

相关文章:

c# - 在c#中删除多种文件类型的文件

c++ - 如何在基类中创建同名的两个函数?

c++ - 使用 "|"中断 Cpp 循环

c++ - char *name 和 char* name 有什么区别?

c# - 想要创建 c# .net 安装程序

c# - 如何强制 CSharpCodeProvider 针对特定目标框架进行编译?

c++ - C++中的双重继承运行时错误

java - 强制子类在抽象 java 类中包含常量

types - 如何声明 TypeScript 导入 * 类型?

c# - 在 WPF 中使用 C# 代码删除 IE 缓存和 Cookie