GetGenericTypeDefinition返回不同类型 [英] GetGenericTypeDefinition returns different types

查看:662
本文介绍了GetGenericTypeDefinition返回不同类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我有以下几种类型

interface IMyInterface<T> { }
class MyClass<T> : IMyInterface<T> { }



为什么以下5条线不会产生相同的结果?

How come the following 5 lines doesn't produce the same outcome?

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();



1型,2型和放大器; TYPE4是相同的。

type1, type2 & type4 are the same

3型和放大器; Type5的是相同的。

type3 & type5 are the same

推荐答案

在三,五的情况下,它的不同的类型;它是 IMyInterface的< SpecificT> ,其中 SpecificT 泛型类型参数(不实际的著名的的,但是从 MyClass的和LT参数本身); T> - 也就是说,它是依赖

In the case of 3 and five, it is a different type; it is the IMyInterface<SpecificT> where SpecificT is the generic type parameter (not the actual known value, but the parameter itself) from MyClass<T> - i.e. it is dependent.

这是完全免费的(独立的) T IMyInterface的<不同; T> ,这是什么1,2和4提供

This is different to the completely free (independent) T in IMyInterface<T>, which is what 1, 2 and 4 provide.

如果您重命名的TS,它变得更加明显:

If you rename the Ts, it becomes more obvious:

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

现在检查 .GetGenericArguments()。单()。名称反目成仇。对于1,2和4是 TA 。对于3和5,是 TB

Now check the .GetGenericArguments().Single().Name against each. For 1, 2 and 4 it is TA. For 3 and 5 it is TB.

这篇关于GetGenericTypeDefinition返回不同类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆