2016-11-23 110 views
1

我使用下面的方法,但在Dictionary它返回TKeyDictionary implements ICollection<KeyValuePair<TKey,TValue>>所以我怎样才能得到 KeyValuePair<TKey,TValue>获取泛型类型out of ICollection

public static Type GetCollectionGenericType(this Type type) 
{ 
    foreach(Type interfaceType in type.GetInterfaces()) 
    { 
     if(interfaceType.IsGenericType && 
      interfaceType.GetGenericTypeDefinition() == typeof(ICollection<>)) 
     { 
      return type.GetGenericArguments()[ 0 ]; 
     } 
    } 
    return null; 
} 

回答

2

Dictionary<>的第一个通用的说法是TKey,这就是你的代码返回。你必须改变你的代码,以得到你正在循环的interfaceType的第一个通用参数。

public static Type GetCollectionGenericType(Type type) 
{ 
    foreach(Type interfaceType in type.GetInterfaces()) 
    { 
     if(interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(ICollection<>)) 
     { 
      return interfaceType.GetGenericArguments()[ 0 ]; 
     } 
    } 
    return null; 
}