如何比较 POCO 之间的字段/属性?

Dan*_* T. 5 c# generics comparison properties poco

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

假设我有一个 POCO:

public class Person
{
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }
    public IList<Person> Relatives { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Nes*_*cio 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; 
    } 
}
Run Code Online (Sandbox Code Playgroud)