假设我有一个类型,MyType。我想做以下事情:
- 查明对于某些 T,MyType 是否实现了 IList 接口。
- 如果 (1) 的答案是肯定的,请找出 T 是什么。
似乎执行此操作的方法是 GetInterface(),但它只能让您按特定名称进行搜索。有没有一种方法可以搜索“所有 IList 形式的接口”(如果可能的话,如果该接口是 IList 的子接口,它也能工作,那么它也会很有用。)
有关的:如何确定类型是否实现特定的泛型接口类型 https://stackoverflow.com/questions/503263/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:即使myType
实施IDerivedFromList<>
但不是直接IList<>
, IList<>
将显示在返回的数组中GetInterfaces()
.
Update:添加了对边缘情况的检查,其中myType
是有问题的通用接口。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)