比较两个对象的属性以发现差异?

比较两个对象的属性以发现差异?,第1张

比较两个对象的属性以发现差异?

是的,通过反思-
假设每种属性类型

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;}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5114010.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-17
下一篇2022-11-17

发表评论

登录后才能评论

评论列表(0条)

    保存