比较两个对象,并找到差异 [英] Compare two objects and find the differences

查看:149
本文介绍了比较两个对象,并找到差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是比较两个对象,并找到差异的最佳方式?

 客户一个=新客户();
客户B =新客户();


解决方案

一个灵活的解决方案:你可以使用反射遍历所有的属性来枚举和确定哪些是和不相等,则返回属性的一些列表并且两个不同值。

下面是一些code这是一个良好的开端,你问的一个例子。只着眼于字段值的权利,但你可以添加任意数目的其他组件为它通过反射检查。它使用一个扩展方法让你所有的物体可以使用它来实现。

要使用

  SomeCustomClass一个=新SomeCustomClass();
    SomeCustomClass B =新SomeCustomClass();
    a.x = 100;
    清单<差额> RT = a.DetailedCompare(二);

我的示例类来比较

 类SomeCustomClass
    {
        公众诠释x = 12;
        公众诠释Y = 13;
    }

和香饽饽

 静态类的一些推广
{
    公共静态列表<差额> DetailedCompare< T>(这件T VAL1,T val2的)
    {
        清单<差额>差异=新的List<差额>();
        字段信息[] F1 = val1.GetType()GetFields()。
        的foreach(在连接字段信息F)
        {
            方差V =新方差();
            v.Prop = f.Name;
            v.valA = f.GetValue(VAL1);
            v.valB = f.GetValue(val2的);
            如果(!v.valA.Equals(v.valB))
                variances.Add(五);        }
        返回差异;
    }
}
类方差
{
    公共字符串道具{搞定;组; }
    公共对象瓦拉{搞定;组; }
    公共对象值Valb {搞定;组; }
}

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

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 (!v.valA.Equals(v.valB))
                variances.Add(v);

        }
        return variances;
    }


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

这篇关于比较两个对象,并找到差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆