【问题标题】:Weird result comparing property values using reflection使用反射比较属性值的奇怪结果
【发布时间】:2009-09-16 20:42:10
【问题描述】:

有人可以解释为什么会这样吗?下面的代码是在 vs2008 的即时窗口中执行的。 prop 是实体框架创建的对象上的 Int32 属性(id 列)。

对象 entity 和 defaultEntity 是使用 Activator.CreateInstance(); 创建的;

Convert.ChangeType(prop.GetValue(entity, null), prop.PropertyType) 0 Convert.ChangeType(prop.GetValue(defaultEntity, null), prop.PropertyType) 0 Convert.ChangeType(prop.GetValue(entity, null), prop.PropertyType) == Convert.ChangeType(prop.GetValue(defaultEntity, null), prop.PropertyType) 假的

【问题讨论】:

    标签: comparison properties


    【解决方案1】:

    我假设您想知道为什么第三行打印错误。如果您想知道为什么前两行打印 0,您必须发布更多代码并告诉我们您的实际预期。

    Convert.ChangeType 返回object。因此,当属性类型实际上是 Int32 时,它将返回一个 boxed 整数。

    您的最后一行是比较两个装箱值的references。实际上你正在做:

    object x = 0;
    object y = 0;
    Console.WriteLine (x == y); // Prints False
    

    您可以改用Equals - 如果这是一个问题,静态object.Equals 方法可以轻松应对空引用:

    object x = 0;
    object y = 0;
    Console.WriteLine (object.Equals(x, y)); // Prints True
    

    【讨论】:

    • 是的,在一位同事的帮助下,我最终弄清楚了这一点。 .Equals 让我得到我想要的。有没有办法在不明确检查每个条件的情况下检查该对象是字符串还是整数?
    • “检查每个条件”是什么意思?您可以使用“is”或调用 GetType()。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    相关资源
    最近更新 更多