您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

是的,通过反思- 假设每种属性类型都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;
}
其他 2022/1/1 18:17:30 有423人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶