找出类型是否实现了通用接口

Ale*_*319 54 .net c# reflection

假设我有一个类型MyType.我想做以下事情:

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

看起来这样做的方法是GetInterface(),但这只允许您按特定名称进行搜索.有没有办法搜索"IList形式的所有接口"(如果可能的话,如果接口是IList的子接口,它也会有用.)

相关:如何确定类型是否实现特定的通用接口类型

Ant*_*hyy 83

// 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] ;
Run Code Online (Sandbox Code Playgroud)

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

更新:添加了边缘情况的检查,其中myType是相关的通用接口.


cas*_*One 11

使用反射(和一些LINQ),您可以轻松地执行此操作:

public static IEnumerable<Type> GetIListTypeParameters(Type type)
{
    // Query.
    return
        from interfaceType in type.GetInterfaces()
        where interfaceType.IsGenericType
        let baseInterface = interfaceType.GetGenericTypeDefinition()
        where baseInterface == typeof(IList<>)
        select interfaceType.GetGenericArguments().First();
}
Run Code Online (Sandbox Code Playgroud)

首先,您将获取该类型的接口,并仅过滤掉那些通用类型的接口.

然后,您将获得这些接口类型的泛型类型定义,并查看它是否与之相同IList<>.

从那里,获得原始接口的泛型参数是一件简单的事情.

请记住,类型可以有多个IList<T>实现,这IEnumerable<Type>就是返回的原因.