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

How to check if type implements ICollection<T>

如何检查给定类型是否是 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> 它将失败。

你可以这样做:

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

您可以尝试使用此代码,它适用于所有集合类型

    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());
        }
    }