public static ToType CloneObject <ToType>(object origin) where ToType : new() { Type type = origin.GetType(); ToType toType = (default(ToType) == null) ? Activator.CreateInstance <ToType>() : default(ToType); Type type2 = toType.GetType(); Cloner.CloneProperties(origin, type, toType, type2); Cloner.CloneFields(origin, type, toType, type2); return(toType); }
public static object CloneObject(object origin, Type targetType) { Type type = origin.GetType(); object obj = null; ConstructorInfo constructorInfo = null; try { obj = Activator.CreateInstance(targetType); } catch { } if (obj == null && type != typeof(string)) { constructorInfo = targetType.GetConstructor(new Type[] { type }); if (constructorInfo != null) { obj = constructorInfo.Invoke(new object[] { origin }); } if (obj == null) { constructorInfo = targetType.GetConstructor(new Type[] { typeof(string) }); } if (constructorInfo != null) { obj = constructorInfo.Invoke(new object[] { origin.ToString() }); } } if (obj == null) { return(null); } if (constructorInfo == null) { Cloner.CloneProperties(origin, type, obj, targetType); Cloner.CloneFields(origin, type, obj, targetType); } return(obj); }