c# - 查明一个类型是否实现了一个泛型接口(interface)

标签 c# .net reflection

假设我有一个类型,MyType。我想执行以下操作:

  1. 查明 MyType 是否为某些 T 实现了 IList 接口(interface)。
  2. 如果 (1) 的答案是肯定的,找出 T 是什么。

执行此操作的方法似乎是 GetInterface(),但它只允许您按特定名称进行搜索。有没有一种方法可以搜索“所有形式为 IList 的接口(interface)”(如果可能的话,如果接口(interface)是 IList 的子接口(interface),它也会有用。)

相关: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] ;

编辑:即使 myType工具 IDerivedFromList<>但不是直接IList<> , IList<>将显示在 GetInterfaces() 返回的数组中.

更新:为myType 的边缘情况添加了检查是有问题的通用接口(interface)。

关于c# - 查明一个类型是否实现了一个泛型接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1121834/

相关文章:

c# - WPF 绑定(bind)到 TextBlock 未更新

c# - 在一个场景中渲染多个对象DirectX C#

c# - OpenSSL 代码 native 工作,但作为 DLL 导致 OPENSSL_Uplink : no OPENSSL_Applink

.net - Control.EndInvoke 为异常重置调用堆栈

c# - 当无法事先知道方法签名时,如何从 MethodInfo 创建委托(delegate)?

c# - 是否可以在 iframe 中加载 .ascx 页面

c# - 如何在 C# 中使用 BCL 拆分字符串而不丢失分隔符?

c# - 在 C# 中使用反射列出枚举中的值

c# - 获取创建对象的类的名称

c# - System.Device.Location.GeoCooperativeWatcher.Position.Location.Speed 始终为 NaN