public static T Duplicate <T>(this T origin) where T : IDataObject, new() { if (origin == null) { return(default(T)); } var t = typeof(T); var ridCol = FiTechBDadosExtensions.RidColumnOf[t]; var idCol = FiTechBDadosExtensions.IdColumnOf[t]; T destination = new T(); ObjectReflector.Open(origin, (objA) => { ObjectReflector.Open(destination, (objB) => { foreach (var field in objB) { if (field.Key.Name == ridCol) { continue; } if (objA.ContainsKey(field.Key.Name)) { objB[field.Key] = objA[field.Key.Name]; } } }); }); return(destination); }
public static void CopyFromAndMergeLists(this Object me, object other) { if (me == null) { throw new NullReferenceException("Figlotech CopyFrom Extension method called on a null value, this is a natural NullReferenceException"); } if (other == null) { me = null; return; } ObjectReflector.Open(other, (objA) => { ObjectReflector.Open(me, (objB) => { foreach (var field in objB) { if (objA.ContainsKey(field.Key.Name)) { var valA = objA[field.Key.Name]; var valB = objB[field.Key.Name]; if ( valA.GetType().IsGenericType&& valA.GetType().Implements(typeof(List <>)) && valB.GetType().IsGenericType&& valB.GetType().Implements(typeof(List <>)) ) { var addMethod = valB.GetType().GetMethods().FirstOrDefault(m => m.Name == "Add" && m.GetParameters().Length == 1); var enny = (IEnumerator)valA.GetType().GetMethods().FirstOrDefault(e => e.Name == "GetEnumerator")?.Invoke(valA, new object[0]); var fodefMethod = valB.GetType().GetMethods().FirstOrDefault(m => m.Name == "FirstOrDefault" && m.GetParameters().Length == 1); while (enny.MoveNext()) { var paramEx = Expression.Parameter(valB.GetType().GetGenericArguments().First(), "a"); var lambda = Expression.Lambda(Expression.Equal(paramEx, Expression.Constant(enny.Current)), paramEx); var fodef = fodefMethod?.Invoke(valB, new object[] { lambda }); if (fodef != null) { if (!fodef.Equals(enny.Current)) { addMethod.Invoke(valB, new object[] { enny.Current }); } else { CopyFromAndMergeLists(fodef, enny.Current); } } } } objB[field.Key] = objA[field.Key.Name]; } } }); }); }