开发者

Compare two objects and find the differences [duplicate]

This question already has answers here: Finding property differences between t开发者_运维百科wo C# objects (8 answers) Closed 7 years ago.

what is the best way to compare two objects and find the differences?

Customer a = new Customer();
Customer b = new Customer();


One Flexible solution: You could use reflection to enumerate through all of the properties and determine which are and are not equal, then return some list of properties and both differing values.

Here's an example of some code that is a good start for what you are asking. It only looks at Field values right now, but you could add any number of other components for it to check through reflection. It's implemented using an extension method so all of your objects could use it.

TO USE

    SomeCustomClass a = new SomeCustomClass();
    SomeCustomClass b = new SomeCustomClass();
    a.x = 100;
    List<Variance> rt = a.DetailedCompare(b);

My sample class to compare against

    class SomeCustomClass
    {
        public int x = 12;
        public int y = 13;
    }

AND THE MEAT AND POTATOES

using System.Collections.Generic;
using System.Reflection;

static class extentions
{
    public static List<Variance> DetailedCompare<T>(this T val1, T val2)
    {
        List<Variance> variances = new List<Variance>();
        FieldInfo[] fi = val1.GetType().GetFields();
        foreach (FieldInfo f in fi)
        {
            Variance v = new Variance();
            v.Prop = f.Name;
            v.valA = f.GetValue(val1);
            v.valB = f.GetValue(val2);
            if (!Equals(v.valA, v.valB))
                variances.Add(v);

        }
        return variances;
    }


}
class Variance
{
    public string Prop { get; set; }
    public object valA { get; set; }
    public object valB { get; set; }
}


The Equals method and the IEquatable<T> interface could be used to know if two objects are equal but they won't allow you to know the differences between the objects. You could use reflection by comparing each property values.

Yet another approach might consist into serializing those instances into some text format and compare the differences inside the resulting strings (XML, JSON, ...).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜