private static ObjectExtensiones.MemberwiseCopyDelegate GetCopyDelegate(Type sourceType, Type targetType, bool ignoreCase) { ObjectExtensiones.MemberwiseCopyDelegate copyDelegate = null; Dictionary <Type, Dictionary <Type, ObjectExtensiones.MemberwiseCopyDelegate> > memberwiseCopyDelegates = ignoreCase ? ObjectExtensiones.memberwiseCopyDelegates_true : ObjectExtensiones.memberwiseCopyDelegates_false; lock (memberwiseCopyDelegates) { if (memberwiseCopyDelegates.ContainsKey(sourceType)) { Dictionary <Type, ObjectExtensiones.MemberwiseCopyDelegate> dict = memberwiseCopyDelegates[sourceType]; if (dict.ContainsKey(targetType)) { copyDelegate = dict[targetType]; } else { copyDelegate = ObjectExtensiones.CreateMemberwiseCopyDelegate(sourceType, targetType, ignoreCase); dict[targetType] = copyDelegate; } } else { Dictionary <Type, ObjectExtensiones.MemberwiseCopyDelegate> dict = new Dictionary <Type, ObjectExtensiones.MemberwiseCopyDelegate>(); memberwiseCopyDelegates.Add(sourceType, dict); copyDelegate = ObjectExtensiones.CreateMemberwiseCopyDelegate(sourceType, targetType, ignoreCase); dict[targetType] = copyDelegate; } } return(copyDelegate); }
/// <summary> /// 浅表复制,将源对象中与目标对象同名的公共非静态字段或属性的值复制到目标对象。 /// 如果字段是值类型的,则对该字段执行逐位复制。 如果字段是引用类型,则复制引用但不复制引用的对象;因此,源对象及当前对象引用同一对象。 /// </summary> public static void MemberwiseCopy(this object source, object target, bool ignoreCase = false) { if (source == null) { throw new ArgumentNullException("source"); } if (target == null) { throw new ArgumentNullException("target"); } ObjectExtensiones.MemberwiseCopyDelegate copyDelegate = ObjectExtensiones.GetCopyDelegate(source.GetType(), target.GetType(), ignoreCase); if (copyDelegate != null) { copyDelegate(source, target); } }
/// <summary> /// 浅表复制,将源对象中与目标对象同名的公共非静态字段或属性的值复制到目标对象。 /// 如果字段是值类型的,则对该字段执行逐位复制。 如果字段是引用类型,则复制引用但不复制引用的对象;因此,源对象及当前对象引用同一对象。 /// 此方法要求 source 类型必须为 TSource 或从其继承,但仅复制源对象中由 TSource 限定的部分字段或属性。 /// </summary> public static void MemberwiseCopy <TSource>(this object source, object target, bool ignoreCase = false) { if (source == null) { throw new ArgumentNullException("source"); } if (target == null) { throw new ArgumentNullException("target"); } if (!typeof(TSource).IsAssignableFrom(source.GetType())) { throw new ArgumentException("源对象的类型不是类型参数指定的类型或其子类。"); } ObjectExtensiones.MemberwiseCopyDelegate copyDelegate = ObjectExtensiones.GetCopyDelegate(typeof(TSource), target.GetType(), ignoreCase); if (copyDelegate != null) { copyDelegate(source, target); } }