2016-11-23 6 views
1

私は以下のメソッドを使用していますが、DictionaryではTKeyを返します。 DictionaryICollection<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; 
} 
関連する問題