检查两个未知类型的对象是否相等,比较所有字段

Sam*_*ser 3 c# reflection equality

我需要定义一个方法来比较同一类型的两个不同对象.对象的类型不是特定的.对象可能是DLL类型,因此我无法覆盖Equals方法.我必须通过反思来做到这一点.如果对象的所有成员都是基本类型,则此代码有效.但是当对象具有非原始字段时,它不起作用.我怎么能通过反思来做到这一点?

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)));
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*out 5

我最近被告知这个lib将完全符合您的要求

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