3 回答
TA贡献1831条经验 获得超4个赞
是的,使用反射 - 假设每种属性类型都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;
}
- 3 回答
- 0 关注
- 1313 浏览
添加回答
举报