differences between two objects in C#

前端 未结 6 459
攒了一身酷
攒了一身酷 2021-01-02 18:29

I was wondering how I would find the difference between two objects of the same class. So if I had a Person class with the only difference being Age it will return the field

6条回答
  •  春和景丽
    2021-01-02 19:19

    What about something like this

    This gets you a list of the property names that are different between the two objects. I don't think this is all the way to the solution you are looking for but I think it is a decent start

    Foo foo1 = new Foo { Prop1 = "One", Prop2 = "Two"};
    Foo foo2 = new Foo { Prop1 = "One", Prop2 = "Three" };
    
    Type fooType = typeof (Foo);
    
    PropertyInfo[] properties = fooType.GetProperties();
    
    var diffs = from property in properties
      let first = foo1
      let second = foo2
      where property.GetValue(first, null) != property.GetValue(second, null)
      select property;
    

    In my example this would return "Prop2" as that is the property whose values differ betwen the objects.

    EDIT: Of course this assumes any complex types in your object implement equality comparisons that do what you expect. If not you would need to dive down the object graph and do nested compares as others have suggested

提交回复
热议问题