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

本文关键字:实现 ICollection 是否 类型 何检查 检查 | 更新日期: 2023-09-27 18:16:11

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

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

你可以这样做:

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