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

标签 c# generics properties comparison poco

<分区>

Possible Duplicate:
Comparing object properties in c#

假设我有一个 POCO:

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

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

我的问题是,如何编写一个通用版本,这样我就不必为每个 POCO 都编写它?

最佳答案

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

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

关于c# - 如何比较 POCO 之间的字段/属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1652897/

相关文章:

java - 关于泛型、有界通配符和 getClass() 的棘手面试问题

java - 使用 Properties 读取 .properties 文件

c# - 从 C# 中的函数中获取当前正在执行的函数的名称

c# - JavaScriptSerializer 可以排除具有空值/默认值的属性吗?

c# - 在网格中绑定(bind) session 数据

c# - Visual Studio 上的奇怪错误 - "you could use the navigation bar to switch context"

c# - 泛型类型推断不考虑多态性

C# 泛型工厂方法

.net - 为什么我们使用 .NET 属性而不是普通的旧 get/set 函数?

C# 自定义属性编辑器