比较两个对象的属性
Comparing the properties of two objects
我有两个相同的对象class:
Car oldCar = new Car()
{
Engine = "V6",
Wheels = 4
}
Car newCar = new Car()
{
Engine = "V8"
Wheels = 4
}
我想比较两个 Car
对象的属性,如果不同(如示例中所示),则打印旧值和更新值,如下所示:
Engine: V6 -> V8
我现在这样做会很不方便,因为我要向 Car 添加更多属性 class:
if(oldCar.Engine != newCar.Engine)
Console.WriteLine(oldCar.Engine + " -> " + newCar.Engine);
如何以更简单的方式完成此操作?我不想手动比较每个 属性.
为此,您可以使用反射。您可以获得对象的所有属性,并对其进行迭代。类似的东西:
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() 的定义。
您可以尝试使用反射:
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));
}
我有两个相同的对象class:
Car oldCar = new Car()
{
Engine = "V6",
Wheels = 4
}
Car newCar = new Car()
{
Engine = "V8"
Wheels = 4
}
我想比较两个 Car
对象的属性,如果不同(如示例中所示),则打印旧值和更新值,如下所示:
Engine: V6 -> V8
我现在这样做会很不方便,因为我要向 Car 添加更多属性 class:
if(oldCar.Engine != newCar.Engine)
Console.WriteLine(oldCar.Engine + " -> " + newCar.Engine);
如何以更简单的方式完成此操作?我不想手动比较每个 属性.
为此,您可以使用反射。您可以获得对象的所有属性,并对其进行迭代。类似的东西:
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() 的定义。
您可以尝试使用反射:
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));
}