differences between two objects in C#

前端 未结 6 455
攒了一身酷
攒了一身酷 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:32

    It really depends on how deep you want to go in comparing the entities, but the idea with reflection is the best one here. The code would be something like that:

    public class Pair
    {
        public object Value1
        {
            get;
            set;
        }
    
        public object Value2
        {
            get;
            set;
        }
    }
    
    //somewhere in another class
    
    public Dictionary Compare(T object1, T object2)
    {
        var props = typeof(T).GetProperties().Where(pi => pi.CanRead); //this will return only public readable properties. Modify if you need something different
        Dictionary result = new Dictionary();
        foreach (var prop in props)
        {
            var val1 = prop.GetValue(object1, null); //indexing properties are ignored here
            var val2 = prop.GetValue(object2, null);
            if (val1 != val2) //maybe some more sophisticated compare algorithm here, using IComparable, nested objects analysis etc.
            {
                result[prop.Name] = new Pair { Value1 = val1, Value2 = val2 };
            }
        }
        return result;
    }
    

    If you need to deeply process nested objects, then, as it was said before, you will need some hash table that will remember already processed objects and prevent them from being processed again. Hope this helps!

提交回复
热议问题