编程语言
首页 > 编程语言> > C#-GetGenericTypeDefinition返回不同的类型

C#-GetGenericTypeDefinition返回不同的类型

作者:互联网

鉴于我有以下几种类型

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相同

类型3和type5相同

解决方法:

在3和5的情况下,它是不同的类型;它是IMyInterface< SpecificT>其中,SpecificT是来自MyClass< T>的通用类型参数(不是实际的已知值,而是参数本身). -即它是依赖的.

这不同于IMyInterfaceT中的完全自由的(独立的)T,这是1、2和4所提供的.

如果重命名Ts,它将变得更加明显:

interface IMyInterface<TA> { }
class MyClass<TB> : IMyInterface<TB> { }

现在,针对每个对象检查.GetGenericArguments().Single().Name.对于1、2和4,它是TA.对于3和5,它是TB.

标签:types,inheritance,type-systems,c
来源: https://codeday.me/bug/20191029/1960667.html