我有一个问题,我想确定一个对象是否属于 KeyValuePair<,> 类型

当我比较时:

else if (item.GetType() == typeof(KeyValuePair<,>))
{
    var key = item.GetType().GetProperty("Key");
    var value = item.GetType().GetProperty("Value");
    var keyObj = key.GetValue(item, null);
    var valueObj = value.GetValue(item, null);
    ...
}

这是错误的,因为 IsGenericTypeDefinition 对他们来说是不同的。

有人可以向我解释为什么会发生这种情况以及如何以正确的方式解决此问题(我的意思是不比较名称或其他琐碎的字段。)

提前谢谢!

最佳答案

item.GetType() == typeof(KeyValuePair<,>)

以上永远不会奏效:不可能创建 KeyValuePair<,> 类型的对象。

原因是 typeof(KeyValuePair<,>) 不代表类型。相反,它是一个泛型类型定义 - 一个 System.Type 对象,用于检查其他泛型类型的结构,但它们本身并不表示有效的 .NET 类型。

如果一个 item 是一个 KeyValuePair<string,int> ,那么 item.GetGenericTypeDefintion() == typeof(KeyValuePair<,>)
以下是修改代码的方法:
...
else if (item.IsGenericType() && item.GetGenericTypeDefintion() == typeof(KeyValuePair<,>)) {
    ...
}

关于c# - 如何比较 IsGenericType Definition 为 def 的相同类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14071379/

10-13 06:53