简体   繁体   English

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

[英]How to compare properties between two objects

I have two similar classes : Person , PersonDto我有两个类似的类: PersonPersonDto

public class Person 
{
    public string Name { get; set; }
    public long Serial { get; set; }
    public DateTime Date1 { get; set; }
    public DateTime? Date2 { get; set; }
}

& &

public class PersonDto
{
    public string Name { get; set; }
    public long Serial { get; set; }
    public DateTime Date1 { get; set; }
    public DateTime? Date2 { get; set; }
}

I have two objects of both by equal values.我有两个值相等的对象。

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

I need to check value of all properties in two classes by reflection.我需要通过反射检查两个类中所有属性的值。 My final goal is defined difference value of this properties.我的最终目标是定义此属性的差异值。

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

I did this, but result is not satisfactory.我这样做了,但结果并不令人满意。 Count of diffProperties for result was 4 but count of my expect was 1 .结果的diffProperties计数为4但我期望的计数为1

Of course all properties can have null values.当然,所有属性都可以有空值。

I need to a solution generic.我需要一个通用的解决方案。 What must do I?我必须做什么?

If you want to stick with comparison via reflection you should not use != (reference equality which will fail most of comparisons for boxed results of GetProperty calls) but instead use static Object.Equals method .如果您想坚持通过反射进行比较,则不应使用 != (引用相等性,这将使大多数 GetProperty 调用的装箱结果的比较失败),而应使用 静态 Object.Equals 方法

Sample how to use Equals method to compare two object in your reflection code.示例如何使用 Equals 方法比较反射代码中的两个对象。

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

您可以考虑使Person类实现IComparable接口并实现CompareTo(Object obj)方法。

Looking at you classes not all values can be null you have a nullable long.看着你的类,并不是所有的值都可以为空,你有一个可以为空的 long。 But that said.但那是说。

I also made something like this and used this website for it.我也做了这样的事情并使用了这个网站 Just make it so that it can accept 2 different objects.只需让它可以接受 2 个不同的对象。 I can't share my code because of licensing sorry.由于许可抱歉,我无法共享我的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM