3 回答

TA貢獻(xiàn)1831條經(jīng)驗 獲得超4個贊
是的,使用反射 - 假設(shè)每種屬性類型都Equals適當(dāng)?shù)貙崿F(xiàn)。另一種方法是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 關(guān)注
- 1347 瀏覽
添加回答
舉報