c# - 比较两个对象的属性以找出差异?

标签 c# .net

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

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

最佳答案

是的,通过反射 - 假设每个属性类型都适本地实现了 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;
}

关于c# - 比较两个对象的属性以找出差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/957783/

相关文章:

c# - Winforms 上的 SQL 更新语句

c# - 获取 map 的 View 边界

c# - yyyyMMddtt 中的 DateTime.ParseExact 错误

.net - 如何在单声道下定位 .NET 4.0

c# - System.DateTime 种类位

.net - 如何将CMS添加到现有网站

c# - ASP.NET MVC2 : How to redirect to GET Details/5 after POST Add

c# - 将职责委派给 WinForm 控件——控件是否应该了解彼此的操作?

.net - 接口(interface)扩展方法的 C# 命名约定

c# - 固定 .NET 对象数组