比较两个对象的属性 [英] Comparing the properties of two objects

查看:98
本文介绍了比较两个对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个相同类的对象:

I have two objects of the same class:

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

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

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

当我添加更多内容时,我目前的操作方式确实很不方便Car类的属性:

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.

推荐答案

为此,您可以使用反射。您可以获得对象的所有属性,并对其进行迭代。像这样的东西:

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

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

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

这篇关于比较两个对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆