C# implementation of deep/recursive object comparison in .net 3.5

后端 未结 6 2215
不思量自难忘°
不思量自难忘° 2020-11-27 16:36

I am looking for a C# specific , open source (or source code available) implementation of recursive, or deep, object comparison.

I currently have two graphs of live

6条回答
  •  我在风中等你
    2020-11-27 17:17

    This is actually a simple process. Using reflection you can compare each field on the object.

    public static Boolean ObjectMatches(Object x, Object y)
    {
        if (x == null && y == null)
            return true;
        else if ((x == null && y != null) || (x != null && y == null))
            return false;       
    
        Type tx = x.GetType();
        Type ty = y.GetType();
    
        if (tx != ty)
            return false;
    
        foreach(FieldInfo field in tx.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
        {
            if (field.FieldType.IsValueType && (field.GetValue(x).ToString() != field.GetValue(y).ToString()))
                return false;
            else if (field.FieldType.IsClass && !ObjectMatches(field.GetValue(x), field.GetValue(y)))
                return false;               
        }
    
        return true;
    }
    

提交回复
热议问题