2016-11-23 1 views
1

다음 방법을 사용하고 있지만 Dictionary에서 TKey을 반환합니다. Dictionary은 어떻게 구현합니까 ICollection<KeyValuePair<TKey,TValue>> 어떻게 얻을 수 있습니까 KeyValuePair<TKey,TValue>?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; 
}