【问题标题】:Comparing the properties of two objects [duplicate]比较两个对象的属性[重复]
【发布时间】:2015-08-26 06:39:08
【问题描述】:

我有两个相同类的对象:

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

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

【问题讨论】:

标签: c# properties comparison


【解决方案1】:

要实现这一点,您可以使用反射。您可以获得对象的所有属性,并对其进行迭代。类似的东西:

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() 的定义。

【讨论】:

    【解决方案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)); 
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多