比较两个对象的属性 [英] Comparing the properties of two objects
问题描述
我有两个相同类的对象:
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屋!