Comparing the properties of two objects [duplicate]

拟墨画扇 提交于 2019-12-11 11:01:18

问题


I have two objects of the same class:

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

I want to compare the properties of the two Car objects, and if different (like in the example), print the old and updated values, like this:

Engine: V6 -> V8

The way I'm doing this at the moment is going to be really inconvenient as I add more properties to the Car class:

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

How can I accomplish this in a simpler way? I don't want to manually compare every single property.


回答1:


To achieve that you can use reflection. You can obtain all the properties of the object, and iterate over it. Something like that:

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();
    }
}

I assume the objects that you use as properties contains a definition of toString().




回答2:


You can try using reflection:

 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)); 
  }


来源:https://stackoverflow.com/questions/32219593/comparing-the-properties-of-two-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!