我有两个相同类型的对象,我想遍历每个对象的公共(public)属性并提醒用户哪些属性不匹配。
是否可以在不知道对象包含哪些属性的情况下执行此操作?
最佳答案
是的,通过反射 - 假设每个属性类型都适本地实现了 Equals
。另一种方法是对除某些已知类型以外的所有类型递归使用 ReflectiveEquals
,但这会变得棘手。
public bool ReflectiveEquals(object first, object second)
{
if (first == null && second == null)
{
return true;
}
if (first == null || second == null)
{
return false;
}
Type firstType = first.GetType();
if (second.GetType() != firstType)
{
return false; // Or throw an exception
}
// This will only use public properties. Is that enough?
foreach (PropertyInfo propertyInfo in firstType.GetProperties())
{
if (propertyInfo.CanRead)
{
object firstValue = propertyInfo.GetValue(first, null);
object secondValue = propertyInfo.GetValue(second, null);
if (!object.Equals(firstValue, secondValue))
{
return false;
}
}
}
return true;
}
关于c# - 比较两个对象的属性以找出差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/957783/