如何检查类型是否实现了ICollection<T>接口

6

我该如何检查一个类型是否实现了ICollection<T>接口?

例如,假设我们有以下变量:

ICollection<object> list = new List<object>();
Type listType = list.GetType();

有没有办法判断listType是否是一个通用的ICollection<>

我已经尝试过以下方法,但没有成功:

if(typeof(ICollection).IsAssignableFrom(listType))
       // ...

if(typeof(ICollection<>).IsAssignableFrom(listType))
      // ...

当然,我可以做以下事情:
if(typeof(ICollection<object>).IsAssignableFrom(listType))
     // ...

但这只适用于 ICollection<object> 类型。如果我有一个 ICollection<string>,它将失败。

2个回答

10

你可以这样做:

bool implements = 
    listType.GetInterfaces()
    .Any(x =>
        x.IsGenericType &&
        x.GetGenericTypeDefinition() == typeof (ICollection<>));

请注意,一个类型可以实现多个具有不同泛型类型的 ICollection<> 接口。 - Andrey Nasonov

1
你可以尝试使用这段代码,它适用于所有集合类型。
    public static class GenericClassifier
    {
        public static bool IsICollection(Type type)
        {
            return Array.Exists(type.GetInterfaces(), IsGenericCollectionType);
        }

        public static bool IsIEnumerable(Type type)
        {
            return Array.Exists(type.GetInterfaces(), IsGenericEnumerableType);
        }

        public static bool IsIList(Type type)
        {
            return Array.Exists(type.GetInterfaces(), IsListCollectionType);
        }

        static bool IsGenericCollectionType(Type type)
        {
            return type.IsGenericType && (typeof(ICollection<>) == type.GetGenericTypeDefinition());
        }

        static bool IsGenericEnumerableType(Type type)
        {
            return type.IsGenericType && (typeof(IEnumerable<>) == type.GetGenericTypeDefinition());
        }

        static bool IsListCollectionType(Type type)
        {
            return type.IsGenericType && (typeof(IList) == type.GetGenericTypeDefinition());
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接