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 的两个实例,看它们是否相等。当然,我会比较 Name
、DateOfBirth
和 Relatives
集合,看看它们是否相等。但是,这将涉及我为每个 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;
}
}