简体   繁体   中英

How to compare properties between two objects

I have two similar classes : 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; }
}

&

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 .

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 .

Sample how to use Equals method to compare two object in your reflection code.

 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. 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. I can't share my code because of licensing sorry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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