如何获取给定Dictionary<TKey,TValue>类型的TKey和TValue的类型?

24
我想要获取给定 Dictionary<TKey,TValue> 类型的 TKey 和 TValue 的类型。
例如,如果类型是 Dictionary<Int32,String>,我想知道如何获取: keyType = typeof(Int32) valueType = typeof(String)

你能解释一下为什么你需要那个吗? - Mitch Wheat
在大多数有用的情况下,你的代码已经知道了类型;要么是直接指定(问题中的 typeof(int) / typeof(string)),要么是通过泛型间接指定 - 这种情况下会是 typeof(TYourKeyType) / typeof(TYourValueType) 之类的形式 - 你是否有 object - Marc Gravell
我需要从序列化文本构建字典。由于字典不可序列化,我们使用自定义格式。然后在重建时,我们需要键和值的类型。 - harsha
1个回答

53

我认为这可能是你要寻找的内容:

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

参考: Type.GetGenericArguments


@Mitch:谢谢;我简直不敢相信我忘了发布文档链接。 - Fredrik Mörk
1
我擅自在您的帖子中添加了链接。 - Mitch Wheat
1
在DotNet Core中,目前的属性是GenericTypeArguments - eltiare

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接