How do I tell whether a Type implements IList<>?

I want to write a method that uses Reflection to tell whether a given Type implements IList<T> . For example:

IsGenericList(typeof(int))                       // should return false
IsGenericList(typeof(ArrayList))                 // should return false
IsGenericList(typeof(IList<int>))                // should return true
IsGenericList(typeof(List<int>))                 // should return true
IsGenericList(typeof(ObservableCollection<int>)) // should return true

In my usage, I can assume that the type will always be an instantiated generic type (or something that's not generic at all).

Unfortunately, this isn't as easy as it ought to be. The obvious solution:

public bool IsGenericList(Type type)
{
    return typeof(IList<>).IsAssignableFrom(type);
}

doesn't work; it always returns false. Apparently non-instantiated generic types like IList<> don't implement IsAssignableFrom the way I'd expect them to: IList<> is not assignable from List<T> .

I've also tried this:

public bool IsGenericList(Type type)
{
    if (!type.IsGenericType)
        return false;
    var genericTypeDefinition = type.GetGenericTypeDefinition();
    return typeof(List<>).IsAssignableFrom(genericTypeDefinition);
}

Ie, turn type into its non-instantiated generic, like IList<int> -> IList<> , and then try IsAssignableFrom again. That will return true when type is an instantiated IList<T> such as IList<int> , IList<object> , etc. But it returns false for classes that implement IList<T> such as List<int> , ObservableCollection<double> , etc., so apparently IList<> is not assignable from List<> . Again, not what I would expect.

How do I go about writing IsGenericList and making it work as in the above examples?


In fact, you cannot have an instance of a generic type definition. Therefore, the IsAssignableFrom() method works as expected. To achieve what you want, do the following:

public bool IsGenericList(Type type)
{
    if (type == null) {
        throw new ArgumentNullException("type");
    }
    foreach (Type @interface in type.GetInterfaces()) {
        if (@interface.IsGenericType) {
            if (@interface.GetGenericTypeDefinition() == typeof(ICollection<>)) {
                // if needed, you can also return the type used as generic argument
                return true;
            }
        }
    }
    return false;
}

Just out of curiosity, what do you need this for?


I too want to test if a type implements IList<T> for some T. I made the obvious change to Lucero's answer but it caused a subtle bug not present in the original answer. Here's my final edit:

    /// <summary>
    /// Test if a type derives from IList of T, for any T.
    /// </summary>
    public bool TestIfGenericList(Type type)
    {
        if (type == null)
        {
            throw new ArgumentNullException("type");
        }

        var interfaceTest = new Predicate<Type>(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>));

        return interfaceTest(type) || type.GetInterfaces().Any(i => interfaceTest(i));
    }

Using this: http://msdn.microsoft.com/en-us/library/system.type.findinterfaces.aspx

I tried this:

 public class Test : IList<string>
 {
//implementation left out...
 }

class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
            TypeFilter myFilter = new TypeFilter(MyInterfaceFilter);

            Type type = t.GetType();
            Type[] x = type.FindInterfaces(myFilter, "System.Collections.Generic.IList");
            Console.WriteLine(x.Length);

        }

        public static bool MyInterfaceFilter(Type typeObj, Object criteriaObj)
        {
            if (typeObj.ToString().Contains(criteriaObj.ToString()))
                return true;
            else
                return false;
        }
    }
链接地址: http://www.djcxy.com/p/57400.html

上一篇: 对'open'泛型类型使用IsAssignableFrom

下一篇: 我如何判断一个Type是否实现IList <>?