5

可能重复:
比较 C# 中的对象属性

假设我有一个 POCO:

public class Person
{
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }
    public IList<Person> Relatives { get; set; }
}

我想比较两个 Person 实例,看看它们是否相等。自然,我会比较Name,DateOfBirthRelatives集合,看看它们是否相等。但是,这将涉及我覆盖Equals()每个 POCO 并手动编写每个字段的比较。

我的问题是,我怎样才能编写一个通用版本,这样我就不必为每个 POCO 都这样做?

4

3 回答 3

5

如果您不担心性能,您可以在实用程序函数中使用反射来迭代每个字段并比较它们的值。

using System; 
using System.Reflection; 


public static class ObjectHelper<t> 
{ 
    public static int Compare(T x, T y) 
    { 
        Type type = typeof(T); 
        var publicBinding = BindingFlags.DeclaredOnly | BindingFlags.Public;
        PropertyInfo[] properties = type.GetProperties(publicBinding); 
        FieldInfo[] fields = type.GetFields(publicBinding); 
        int compareValue = 0; 


        foreach (PropertyInfo property in properties) 
        { 
            IComparable valx = property.GetValue(x, null) as IComparable; 
            if (valx == null) 
                continue; 
            object valy = property.GetValue(y, null); 
            compareValue = valx.CompareTo(valy); 
            if (compareValue != 0) 
                return compareValue; 
        } 
        foreach (FieldInfo field in fields) 
        { 
            IComparable valx = field.GetValue(x) as IComparable; 
            if (valx == null) 
                continue; 
            object valy = field.GetValue(y); 
            compareValue = valx.CompareTo(valy); 
            if (compareValue != 0) 
                return compareValue; 
        } 
    return compareValue; 
    } 
}
于 2009-10-31T00:10:03.423 回答
2

可以使用反射以一般方式执行此操作,但它具有性能和复杂性的缺点。最好手动实施EqualsGetHashCode这样您就可以获得预期的结果。

请参阅我应该重载 == 运算符吗?

于 2009-10-31T00:09:57.323 回答
1

实现 Equals() 和 GetHashCode() 并不麻烦。

public override bool Equals(object obj)
{
    if (ReferenceEquals(this, obj) return true;
    if (!(obj is Person)) return false;

    var other = (Person) obj;
    return this == other;
}

public override int GetHashCode()
{
    return base.GetHashCode();
}

请参阅有效地使用 Equals/GetHashCode

于 2009-10-31T09:28:25.550 回答