检查两个未知类型的对象是否相等,比较它们的所有字段 [英] Check two object, of unknown type, for equality, comparing all their fields

查看:132
本文介绍了检查两个未知类型的对象是否相等,比较它们的所有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要定义一个方法来比较相同类型的两个不同对象。对象的类型不是特定的。这些对象可能是DLL类型,因此无法覆盖等于方法。我必须通过反思来做到这一点。如果对象的所有成员均为原始类型,则此代码有效。但是,当对象的字段不是原始字段时,此方法将无效。

I need to define a method to compare two different objects of a same type. The type of objects is not specific. The objects may be a DLL type, so I can't override Equals method. I have to do this by reflection. This code works if all the members of objects are of primitive type. But it doesn't work when an object has a field that isn't primitive. How can I do it by reflection?

public bool Equals(object obj1, object obj2)
{
    List<FieldInfo> fieldInfos =  obj1.GetType().GetFields().ToList();
    return (fieldInfos.Select(fieldInfo => new {fieldInfo, type = fieldInfo.GetType()})
        .Where(@t => @t.type.IsPrimitive || @t.type == typeof(string) || @t.type == typeof(Decimal))
        .Select(@t => @t.fieldInfo)).All(fieldInfo => fieldInfo.GetValue(obj1).Equals(fieldInfo.GetValue(obj2)));
}


推荐答案

最近有人告诉我此库将完全满足您的需求

I have recently been told about this lib that will do exactly what you are wanting

http://comparenetobjects.codeplex.com/releases/view/47978

这篇关于检查两个未知类型的对象是否相等,比较它们的所有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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