3

我有一个问题,我想确定一个对象是否属于类型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对他们来说是不同的。

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

提前谢谢!

4

2 回答 2

2

找到这段代码,试一试:

public bool IsKeyValuePair(object o) 
{
    Type type = o.GetType();

    if (type.IsGenericType)
    {
        return type.GetGenericTypeDefinition() != null ? type.GetGenericTypeDefinition() == typeof(KeyValuePair<,>) : false;
    }

    return false;
}

资源:

http://social.msdn.microsoft.com/Forums/hu-HU/csharpgeneral/thread/9ad76a19-ed9c-4a02-be6b-95870af0e10b

于 2012-12-28T15:00:00.410 回答
2
item.GetType() == typeof(KeyValuePair<,>)

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

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

如果 anitem是,比如说, a KeyValuePair<string,int>,那么item.GetGenericTypeDefintion() == typeof(KeyValuePair<,>)

以下是修改代码的方法:

...
else if (item.IsGenericType() && item.GetGenericTypeDefintion() == typeof(KeyValuePair<,>)) {
    ...
}
于 2012-12-28T15:06:39.163 回答