发现如果一个类型实现一个通用接口 [英] Finding out if a type implements a generic interface

查看:183
本文介绍了发现如果一个类型实现一个通用接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个类型,MyType的。我要做到以下几点:

  1. 找到了,如果MyType的实现了IList接口,对于某些吨。
  2. 如果答案(1)是肯定的,找出T是什么。

好像要做到这一点的方法是GetInterface(),但只允许通过一个特定的名称进行搜索。有没有一种方法来搜索是形式的IList的所有接口(如果可能的话,也woudl是有用的,如果它的工作,如果接口是IList中的子接口。)

相关阅读:<一href="http://stackoverflow.com/questions/503263/how-to-determine-if-a-type-implements-a-specific-generic-interface-type">How以确定是否类型实现一个特定的通用接口类型的

解决方案

  //这个条件是必要的,如果可以的myType是一个接口,
//因为接口不实现自己的:例如,
// typeof运算(IList的&LT; INT&GT;)。GetInterfaces()不包含的IList&LT; INT&GT;!
如果(myType.IsInterface&安培;&安培; myType.IsGenericType和放大器;&安培;
    myType.GetGenericTypeDefinition()== typeof运算(IList的&LT;&GT;))
    返回myType.GetGenericArguments()[0];

的foreach(在myType.GetInterfaces变种I())
    如果(i.IsGenericType&安培;&安培; i.GetGenericTypeDefinition()== typeof运算(IList的&LT;&GT;))
        返回i.GetGenericArguments()[0];
 

编辑:的即使的myType 工具 IDerivedFromList&LT;&GT; 但不能直接的IList&LT;&GT; 的IList&LT;&GT; GetInterfaces返回的数组中显示出来( )

更新:增加了边缘的情况下,其中的myType 是有问题的通用接口检查

Let's say I have a type, MyType. I want to do the following:

  1. Find out if MyType implements the IList interface, for some T.
  2. If the answer to (1) is yes, find out what T is.

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.)

Related: How to determine if a type implements a specific generic interface type

解决方案

// 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] ;

Edit: Even if myType implements IDerivedFromList<> but not directly IList<>, IList<> will show up in the array returned by GetInterfaces().

Update: added a check for the edge case where myType is the generic interface in question.

这篇关于发现如果一个类型实现一个通用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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