比较两个对象的属性

时间:2015-08-26 06:39:08

标签: c# properties comparison

我有两个同一类的对象:

Car oldCar = new Car()
{
   Engine = "V6",
   Wheels = 4
}
Car newCar = new Car()
{
   Engine = "V8"
   Wheels = 4
}

我想比较两个Car对象的属性,如果不同(如示例中所示),则打印旧的和更新的值,如下所示:

Engine: V6 -> V8

当我向Car类添加更多属性时,我现在这样做的方式会非常不方便:

if(oldCar.Engine != newCar.Engine)
   Console.WriteLine(oldCar.Engine + " -> " + newCar.Engine);

如何以更简单的方式完成此操作?我不想手动比较每一个属性。

2 个答案:

答案 0 :(得分:4)

要实现这一目标,您可以使用反射。您可以获取对象的所有属性,并迭代它。这样的事情:

void CompareCars(Car oldCar, Car newCar) 
{
    Type type = oldCar.GetType();
    PropertyInfo[] properties = type.GetProperties();

    foreach (PropertyInfo property in properties)
    {
        object oldCarValue = property.GetValue(oldCar, null); 
        object newCarValue = property.GetValue(newCar, null); 
        Console.WriteLine("oldCar." + property.Name +": " + oldCarValue.toString() " -> "  + "newCar." + property.Name +": " newCarValue.toString();
    }
}

我假设您用作属性的对象包含toString()的定义。

答案 1 :(得分:2)

您可以尝试使用反射:

 using System.Reflection;
 ...

 // Let's check public properties that can be read and written (i.e. changed)
 var props = typeof(Car)
    .GetProperties(BindingFlags.Public | BindingFlags.Instance)
    .Where(prop => prop.CanRead && prop.CanWrite);

  foreach (var property in props) {
    Object oldValue = property.GetValue(oldCar);
    Object newValue = property.GetValue(newCar);

    if (!Object.Equals(oldValue, newValue)) 
      Console.WriteLine(String.Format("{0}: {1} -> {2}", 
        property.Name, 
        oldValue, 
        newValue)); 
  }