如何比较定义了IsGenericTypeDefinition的相同类型

本文关键字:IsGenericTypeDefinition 同类型 定义 何比较 比较 | 更新日期: 2023-09-27 17:49:41

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

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

提前感谢!

如何比较定义了IsGenericTypeDefinition的相同类型

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

上面的方法行不通:不可能创建一个类型为KeyValuePair<,>的对象。

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

如果itemKeyValuePair<string,int>,那么item.GetGenericTypeDefintion() == typeof(KeyValuePair<,>)

下面是修改代码的方法:
...
else if (item.IsGenericType() && item.GetGenericTypeDefintion() == typeof(KeyValuePair<,>)) {
    ...
}

找到这段代码,试一下:

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 - 4 - a02 be6b - 95870 af0e10b

相关文章:
  • 没有找到相关文章