C# 比较使用PropertyInfo.GetValue()检索的值时出现意外结果

C# 比较使用PropertyInfo.GetValue()检索的值时出现意外结果,c#,reflection,properties,comparison,C#,Reflection,Properties,Comparison,我有一些代码,我用它来循环某些对象的属性并比较属性值,看起来有点像这样: public static bool AreObjectPropertyValuesEqual(object a, object b) { if (a.GetType() != b.GetType()) throw new ArgumentException("The objects must be of the same type."); Type type = a.GetType(); foreach

我有一些代码,我用它来循环某些对象的属性并比较属性值,看起来有点像这样:

public static bool AreObjectPropertyValuesEqual(object a, object b)
{

 if (a.GetType() != b.GetType())
  throw new ArgumentException("The objects must be of the same type.");

 Type type = a.GetType();

 foreach (PropertyInfo propInfo in type.GetProperties())
 {
  if (propInfo.GetValue(a, null) != propInfo.GetValue(b, null))
  {
   return false;
  }
 }
 return true;
}
现在来看看奇怪的行为。我创建了一个名为PurchaseOrder的类,其中包含两个属性,所有属性都是简单的数据类型(字符串、整数等)。我在单元测试代码中创建了一个实例,另一个实例由我的DataModel创建,从数据库中获取数据(MySql,我使用的是MySqlConnector)

尽管调试器向我显示属性值相同,但上面代码中的比较失败

也就是说:我在UnitTest中创建的对象A的Amount属性值为10。从我的存储库检索到的对象B的Amount属性值为10。比较失败!如果我把代码改成

if (propInfo.GetValue(a, null).ToString() != propInfo.GetValue(b, null).ToString())
{
 ...
}
一切都如我所料。如果我直接在UnitTest中创建PurchaseOrder实例,比较也不会失败


我会非常感谢你的回答。祝你有愉快的一天

失败的原因是上面应用的相等测试是一个参考相等测试。由于
propInfo.GetValue(foo,null)
返回的两个对象虽然根据各自的定义相等,但它们是独立的对象,它们的引用不同,因此相等失败。

PropertyInfo.GetValue返回一个对象,单元测试正在进行==引用比较。请尝试以下方法:

if (!propInfo.GetValue(a, null).Equals(propInfo.GetValue(b, null)))
您可能想用更合理的方法替换
null

或者,您可以尝试:

if ((int?)propInfo.GetValue(a, null) != (int?)propInfo.GetValue(b, null))

(或者,如果不是强制值类型==行为的
int
,则可以使用任何简单类型。

非常有效,非常感谢。其中有null,因为我不想让代码样本过于复杂。我本可以早点考虑的。:)谢谢你的回复!