找出一个类型是否实现了泛型接口 [英] Finding out if a type implements a generic interface
问题描述
假设我有一个类型,MyType.我想做以下事情:
Let's say I have a type, MyType. I want to do the following:
- 找出 MyType 是否为某些 T 实现了 IList 接口.
- 如果 (1) 的答案是肯定的,找出 T 是什么.
似乎这样做的方法是 GetInterface(),但这只能让您按特定名称进行搜索.有没有办法搜索所有 IList 形式的接口"(如果可能的话,如果接口是 IList 的子接口,它也很有用.)
It seems like the way to do this is GetInterface(), but that only lets you search by a specific name. Is there a way to search for "all interfaces that are of the form IList" (If possible it woudl also be useful if it worked if the interface was a subinterface of IList.)
推荐答案
// this conditional is necessary if myType can be an interface,
// because an interface doesn't implement itself: for example,
// typeof (IList<int>).GetInterfaces () does not contain IList<int>!
if (myType.IsInterface && myType.IsGenericType &&
myType.GetGenericTypeDefinition () == typeof (IList<>))
return myType.GetGenericArguments ()[0] ;
foreach (var i in myType.GetInterfaces ())
if (i.IsGenericType && i.GetGenericTypeDefinition () == typeof (IList<>))
return i.GetGenericArguments ()[0] ;
即使 myType
实现了 IDerivedFromList<>
但不是直接实现 IList<>
,IList<>
将显示在 GetInterfaces()
返回的数组中.
Even if myType
implements IDerivedFromList<>
but not directly IList<>
, IList<>
will show up in the array returned by GetInterfaces()
.
更新:添加了对myType
是相关通用接口的边缘情况的检查.
Update: added a check for the edge case where myType
is the generic interface in question.
这篇关于找出一个类型是否实现了泛型接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!