52

如何确定类型是否属于Dictionary<,>

目前唯一对我有用的是我是否真的知道这些论点。

例如:

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

但是字典并不总是<string, object>如此,我如何在不知道参数且不必检查名称的情况下检查它是否是字典(因为我们还有其他包含单词Dictionary.

4

4 回答 4

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

然后您可以获取键和值类型:

Type keyType = t.GetGenericArguments()[0];
Type valueType = t.GetGenericArguments()[1];
于 2013-06-06T08:16:39.037 回答
8

您可以使用IsAssignableFrom来检查类型是否实现IDictionary

var dict = new Dictionary<string, object>();

var isDict = typeof(IDictionary).IsAssignableFrom(dict.GetType());

Console.WriteLine(isDict); //prints true

此代码将为所有未实现IDictionary接口的类型打印 false。

于 2013-06-06T08:18:59.563 回答
6

有一个非常简单的方法可以做到这一点,你就快到了。

尝试这个:

var dict = new Dictionary<string, object>();
var isDict = (dict.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>))
于 2013-06-06T08:21:59.623 回答
1

怎么样

Dictionary<string, object> d = new Dictionary<string, object>();
Dictionary<int, string> d2 = new Dictionary<int, string>();
List<string> d3 = new List<string>();

Console.WriteLine(d is System.Collections.IDictionary);
Console.WriteLine(d2 is System.Collections.IDictionary);
Console.WriteLine(d3 is System.Collections.IDictionary);

由于所有通用 Dictionary 类型都继承自 IDictionary 接口,因此您可以检查一下

于 2013-06-06T08:29:09.707 回答