比较两个对象的属性以发现差异? [英] Compare two objects' properties to find differences?

查看:242
本文介绍了比较两个对象的属性以发现差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个相同类型的对象,我想遍历每个对象的公共属性,并提醒用户哪些属性不匹配。

I have two objects of the same type, and I want to loop through the public properties on each of them and alert the user about which properties don't match.

是否可以在不知道对象包含哪些属性的情况下执行此操作?

Is it possible to do this without knowing what properties the object contains?

推荐答案

是的,通过反射-假定每种属性类型适当地实现等于。另一种选择是对除某些已知类型以外的所有其他类型递归使用 ReflectiveEquals ,但这会很棘手。

Yes, with reflection - assuming each property type implements Equals appropriately. An alternative would be to use ReflectiveEquals recursively for all but some known types, but that gets tricky.

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

这篇关于比较两个对象的属性以发现差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆