2015-10-05 61 views
3

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

回答

6

你可以这样说:

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

注意,一个类型可以实现多个'ICollection的<>'接口与不同的通用类型。 –

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()); 
     } 
    } 
相关问题