给定一个Dictionary <tkey,tvalue> type </tkey,tvalue>如何获取TKey和TValue的类型

时间:2010-03-08 06:44:01

标签: c# generics reflection

我希望获得Dictionary<TKey,TValue>类型的TKey和TValue类型。

例如。如果type为Dictionary<Int32,String>,我想知道如何获取 keyType = typeof(Int32)和 valueType = typeof(String)

1 个答案:

答案 0 :(得分:38)

我想这可能就是你要找的东西:

Dictionary<int, string> dictionary = new Dictionary<int, string>();
Type[] arguments = dictionary.GetType().GetGenericArguments();
Type keyType = arguments[0];
Type valueType = arguments[1];

参考:Type.GetGenericArguments