假设我有一个类型,MyType。我想执行以下操作:
- 查明 MyType 是否为某些 T 实现了 IList 接口(interface)。
- 如果 (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/