如何比较两个对象之间的属性

Ehs*_*san 6 c# reflection

我有两个相似的类:Person,PersonDto

public class Person 
{
    public string Name { get; set; }
    public long Serial { get; set; }
    public DateTime Date1 { get; set; }
    public DateTime? Date2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

&

public class PersonDto
{
    public string Name { get; set; }
    public long Serial { get; set; }
    public DateTime Date1 { get; set; }
    public DateTime? Date2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我有两个由两个值相等的对象.

    var person = new Person { Name = null , Serial = 123, Date1 = DateTime.Now.Date, Date2 = DateTime.Now.Date };
    var dto = new PersonDto { Name = "AAA", Serial = 123, Date1 = DateTime.Now.Date, Date2 = DateTime.Now.Date };
Run Code Online (Sandbox Code Playgroud)

我需要通过反射检查两个类中所有属性的值.我的最终目标是定义此属性的差异值.

    IList diffProperties = new ArrayList();
    foreach (var item in person.GetType().GetProperties())
    {
        if (item.GetValue(person, null) != dto.GetType().GetProperty(item.Name).GetValue(dto, null))
            diffProperties.Add(item);
    }
Run Code Online (Sandbox Code Playgroud)

我这样做了,但结果并不令人满意.计数diffProperties的结果4,但我期待计数1.

当然,所有属性都可以具有空值.

我需要一个通用的解决方案.我该怎么办?

M.A*_*zad 12

如果你想坚持通过反射进行比较,你不应该使用!=(引用相等,这将使大多数比较失败的GetProperty调用的盒装结果),而是使用静态Object.Equals方法.

示例如何使用Equals方法比较反射代码中的两个对象.

 if (!Object.Equals(
     item.GetValue(person, null),
     dto.GetType().GetProperty(item.Name).GetValue(dto, null)))
 { 
   diffProperties.Add(item);
 } 
Run Code Online (Sandbox Code Playgroud)