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

Mat*_*ats 4 c# reflection comparison properties

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

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;
}
Run Code Online (Sandbox Code Playgroud)

现在为了奇怪的行为.我创建了一个名为PurchaseOrder的类,它有几个属性,所有属性都是简单的数据类型(字符串,整数等).我在Unit-Test代码中创建了一个实例,另一个是由我的DataModel创建的,从数据库中获取数据(MySql,我正在使用MySqlConnector).

虽然调试器告诉我,属性值是相同的,但上面代码中的比较失败了.

即:我在UnitTest中创建的对象A的Amount属性值为10.从我的Repository中检索的对象B的Amount属性值为10.比较失败!如果我将代码更改为

if (propInfo.GetValue(a, null).ToString() != propInfo.GetValue(b, null).ToString())
{
 ...
}
Run Code Online (Sandbox Code Playgroud)

一切都按照我的预期运作.如果我直接在UnitTest中创建PurchaseOrder实例,那么比较也不会失败.

我会非常感谢任何回答.祝你有美好的一天!

Dav*_*d M 6

PropertyInfo.GetValue返回一个对象,您的单元测试正在进行==引用比较.试试这个:

if (!propInfo.GetValue(a, null).Equals(propInfo.GetValue(b, null)))
Run Code Online (Sandbox Code Playgroud)

你可能想换null一些更明智的东西......

或者,您可以尝试:

if ((int?)propInfo.GetValue(a, null) != (int?)propInfo.GetValue(b, null))
Run Code Online (Sandbox Code Playgroud)

(或者如果它不是一个简单的类型int)强制值类型==行为.