确定类型是否为字典

The*_*der 40 c# generics dictionary

如何判断Type是否为 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
Run Code Online (Sandbox Code Playgroud)

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

Lee*_*Lee 78

Type t = dict.GetType();
bool isDict = t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>);
Run Code Online (Sandbox Code Playgroud)

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

Type keyType = t.GetGenericArguments()[0];
Type valueType = t.GetGenericArguments()[1];
Run Code Online (Sandbox Code Playgroud)


Ily*_*nov 5

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

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

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

Console.WriteLine(isDict); //prints true
Run Code Online (Sandbox Code Playgroud)

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


0b1*_*010 5

有一个非常简单的方法来做到这一点,你几乎就在那里.

试试这个:

var dict = new Dictionary<string, object>();
var isDict = (dict.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>))
Run Code Online (Sandbox Code Playgroud)