确定是否类型是字典 [英] Determine if type is dictionary

查看:161
本文介绍了确定是否类型是字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确定类型为字典<,>



目前的工作的唯一的事。对我来说,如果我真的知道的参数



例如:

  VAR字典=新词典<字符串对象>(); 
VAR isDict = dict.GetType()== typeof运算(字典<字符串对象> ;; //这个作品
VAR isDict = dict.GetType()== typeof运算(字典<,取代; ​​/ /这不起作用

但字典不会永远是<字符串,对象> 让我怎么能检查它是否是一个字典不知道的争论,也不必检查名字(因为我们也有包含单词其他类词典


解决方案

 键入t = dict.GetType(); 
布尔isDict = t.IsGenericType&放大器;&安培; t.GetGenericTypeDefinition()== typeof运算(字典<,>);

然后就可以拿到钥匙和值类型:

 键入关键字类型= t.GetGenericArguments( )[0]; 
类型的ValueType = t.GetGenericArguments()[1];


How can I determine if Type is of Dictionary<,>

Currently the only thing that worked for me is if I actually know the arguments.

For example:

var dict = new Dictionary<string, object>();
var isDict = dict.GetType() == typeof(Dictionary<string, object>; // This Works
var isDict = dict.GetType() == typeof(Dictionary<,>; // This does not work

But the dictionary won't always be <string, object> so how can I check whether it's a dictionary without knowing the arguments and without having to check the name (since we also have other classes that contain the word Dictionary.

解决方案

Type t = dict.GetType();
bool isDict = t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>);

You can then get the key and value types:

Type keyType = t.GetGenericArguments()[0];
Type valueType = t.GetGenericArguments()[1];

这篇关于确定是否类型是字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆