mardi 12 juillet 2016

C# - Generic method for object audit with nested complex properties like list and iEnumeable

I am trying to create a generic method, which takes two object as parameters and compares every property within the objects and return the differences. Now I am implementing this using reflection and this works fine for the simple properties(int, string....).

But when it comes to complex data types like a list, array etc. I need to track the number of elements in those lists added or removed. I am trying to figure out the same using below code but am kind of stuck for complex types.

Any suggestions to proceed are appreciated.

Thanks!!

private static string GenerateAuditLogMessage<T>(T oldObject, T newObject)
  {
     PropertyInfo[] properties = typeof(T).GetProperties();
     foreach (PropertyInfo pi in properties)
     {
        object oldValue = pi.GetValue(oldObject), newValue = pi.GetValue(newObject);

        if (pi.PropertyType.IsGenericType && typeof(IEnumerable).IsAssignableFrom(pi.PropertyType))
        {
           Type type = oldValue.GetType().GetGenericArguments()[0];

           /* Need something like below commented line.*/
           // var added = newValue.Except(oldValue)
           // var removed = oldValue.Except(newValue);
        }
        else
        {
           if (!object.Equals(oldValue, newValue))
           {
             //....
           }
        }
     }

     return string.Empty;
  }





Aucun commentaire:

Enregistrer un commentaire