- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Reflection.Emit;
- using System.Text;
-
-
- namespace Care.Common
- {
- public static class ObjectCopy
- {
- struct Identity
- {
- int _hashcode;
- RuntimeTypeHandle _type;
-
-
- public Identity(int hashcode, RuntimeTypeHandle type)
- {
- _hashcode = hashcode;
- _type = type;
- }
- }
- //緩存對象複製的方法。
- static Dictionary<Type, Func<object, Dictionary<Identity, object>, object>> methods1 = new Dictionary<Type, Func<object, Dictionary<Identity, object>, object>>();
- static Dictionary<Type, Action<object, Dictionary<Identity, object>, object>> methods2 = new Dictionary<Type, Action<object, Dictionary<Identity, object>, object>>();
-
-
- static List<FieldInfo> GetSettableFields(Type t)
- {
- return t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).ToList();
- }
-
-
- static Func<object, Dictionary<Identity, object>, object> CreateCloneMethod1(Type type, Dictionary<Identity, object> objects)
- {
- Type tmptype;
- var fields = GetSettableFields(type);
- var dm = new DynamicMethod(string.Format("Clone{0}", Guid.NewGuid()), typeof(object), new[] { typeof(object), typeof(Dictionary<Identity, object>) }, true);
- var il = dm.GetILGenerator();
- il.DeclareLocal(type);
- il.DeclareLocal(type);
- il.DeclareLocal(typeof(Identity));
- if (!type.IsArray)
- {
- il.Emit(OpCodes.Newobj, type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null));
- il.Emit(OpCodes.Dup);
- il.Emit(OpCodes.Stloc_1);
- il.Emit(OpCodes.Ldloca_S, 2);
- il.Emit(OpCodes.Ldarg_0);
- il.Emit(OpCodes.Castclass, type);
- il.Emit(OpCodes.Dup);
- il.Emit(OpCodes.Stloc_0);
- il.Emit(OpCodes.Callvirt, typeof(object).GetMethod("GetHashCode"));
- il.Emit(OpCodes.Ldtoken, type);
- il.Emit(OpCodes.Call, typeof(Identity).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new[] { typeof(int), typeof(RuntimeTypeHandle) }, null));
- il.Emit(OpCodes.Ldarg_1);
- il.Emit(OpCodes.Ldloc_2);
- il.Emit(OpCodes.Ldloc_1);
- il.Emit(OpCodes.Callvirt, typeof(Dictionary<Identity, object>).GetMethod("Add"));
- foreach (var field in fields)
- {
- if (!field.FieldType.IsValueType && field.FieldType != typeof(String))
- {
- //不符合條件的字段,直接忽略,避免報錯。
- if ((field.FieldType.IsArray && (field.FieldType.GetArrayRank() > 1 || (!(tmptype = field.FieldType.GetElementType()).IsValueType && tmptype != typeof(String) && tmptype.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null) == null))) ||
- (!field.FieldType.IsArray && field.FieldType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null) == null))
- break;
- il.Emit(OpCodes.Ldloc_1);
- il.Emit(OpCodes.Ldloc_0);
- il.Emit(OpCodes.Ldfld, field);
- il.Emit(OpCodes.Ldarg_1);
- il.EmitCall(OpCodes.Call, typeof(ObjectCopy).GetMethod("CopyImpl", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(field.FieldType), null);
- il.Emit(OpCodes.Stfld, field);
- }
- else
- {
- il.Emit(OpCodes.Ldloc_1);
- il.Emit(OpCodes.Ldloc_0);
- il.Emit(OpCodes.Ldfld, field);
- il.Emit(OpCodes.Stfld, field);
- }
- }
- for (type = type.BaseType; type != null && type != typeof(object); type = type.BaseType)
- {
- //只須要查找基類的私有成員,共有或受保護的在派生類中直接被複制過了。
- fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance).ToList();
- foreach (var field in fields)
- {
- if (!field.FieldType.IsValueType && field.FieldType != typeof(String))
- {
- //不符合條件的字段,直接忽略,避免報錯。
- if ((field.FieldType.IsArray && (field.FieldType.GetArrayRank() > 1 || (!(tmptype = field.FieldType.GetElementType()).IsValueType && tmptype != typeof(String) && tmptype.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null) == null))) ||
- (!field.FieldType.IsArray && field.FieldType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null) == null))
- break;
- il.Emit(OpCodes.Ldloc_1);
- il.Emit(OpCodes.Ldloc_0);
- il.Emit(OpCodes.Ldfld, field);
- il.Emit(OpCodes.Ldarg_1);
- il.EmitCall(OpCodes.Call, typeof(ObjectCopy).GetMethod("CopyImpl", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(field.FieldType), null);
- il.Emit(OpCodes.Stfld, field);
- }
- else
- {
- il.Emit(OpCodes.Ldloc_1);
- il.Emit(OpCodes.Ldloc_0);
- il.Emit(OpCodes.Ldfld, field);
- il.Emit(OpCodes.Stfld, field);
- }
- }
- }
- }
- else
- {
- Type arraytype = type.GetElementType();
- var i = il.DeclareLocal(typeof(int));
- var lb1 = il.DefineLabel();
- var lb2 = il.DefineLabel();
- il.Emit(OpCodes.Ldarg_0);
- il.Emit(OpCodes.Castclass, type);
- il.Emit(OpCodes.Dup);
- il.Emit(OpCodes.Stloc_0);
- il.Emit(OpCodes.Ldlen);
- il.Emit(OpCodes.Dup);
- il.Emit(OpCodes.Ldc_I4_1);
- il.Emit(OpCodes.Sub);
- il.Emit(OpCodes.Stloc, i);
- il.Emit(OpCodes.Newarr, arraytype);
- il.Emit(OpCodes.Dup);
- il.Emit(OpCodes.Stloc_1);
- il.Emit(OpCodes.Ldloca_S, 2);
- il.Emit(OpCodes.Ldloc_0);
- il.Emit(OpCodes.Callvirt, typeof(object).GetMethod("GetHashCode"));
- il.Emit(OpCodes.Ldtoken, type);
- il.Emit(OpCodes.Call, typeof(Identity).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new[] { typeof(int), typeof(RuntimeTypeHandle) }, null));
- il.Emit(OpCodes.Ldarg_1);
- il.Emit(OpCodes.Ldloc_2);
- il.Emit(OpCodes.Ldloc_1);
- il.Emit(OpCodes.Callvirt, typeof(Dictionary<Identity, object>).GetMethod("Add"));
- il.Emit(OpCodes.Ldloc, i);
- il.Emit(OpCodes.Br, lb1);
- il.MarkLabel(lb2);
- il.Emit(OpCodes.Dup);
- il.Emit(OpCodes.Ldloc, i);
- il.Emit(OpCodes.Ldloc_0);
- il.Emit(OpCodes.Ldloc, i);
- il.Emit(OpCodes.Ldelem, arraytype);
- if (!arraytype.IsValueType && arraytype != typeof(String))
- {
- il.EmitCall(OpCodes.Call, typeof(ObjectCopy).GetMethod("CopyImpl", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(arraytype), null);
- }
- il.Emit(OpCodes.Stelem, arraytype);
- il.Emit(OpCodes.Ldloc, i);
- il.Emit(OpCodes.Ldc_I4_1);
- il.Emit(OpCodes.Sub);
- il.Emit(OpCodes.Dup);
- il.Emit(OpCodes.Stloc, i);
- il.MarkLabel(lb1);
- il.Emit(OpCodes.Ldc_I4_0);
- il.Emit(OpCodes.Clt);
- il.Emit(OpCodes.Brfalse, lb2);
- }
- il.Emit(OpCodes.Ret);
-
-
- return (Func<object, Dictionary<Identity, object>, object>)dm.CreateDelegate(typeof(Func<object, Dictionary<Identity, object>, object>));
- }
-
- static Action<object, Dictionary<Identity, object>, object> CreateCloneMethod2(Type type, Dictionary<Identity, object> objects)
- {
- Type tmptype;
- var fields = GetSettableFields(type);
- var dm = new DynamicMethod(string.Format("Copy{0}", Guid.NewGuid()), null, new[] { typeof(object), typeof(Dictionary<Identity, object>), typeof(object) }, true);
- var il = dm.GetILGenerator();
- il.DeclareLocal(type);
- il.DeclareLocal(type);
- il.DeclareLocal(typeof(Identity));
- if (!type.IsArray)
- {
- il.Emit(OpCodes.Ldarg_2);
- il.Emit(OpCodes.Castclass, type);
- il.Emit(OpCodes.Stloc_1);
- il.Emit(OpCodes.Ldarg_0);
- il.Emit(OpCodes.Castclass, type);
- il.Emit(OpCodes.Stloc_0);
- foreach (var field in fields)
- {
- if (!field.FieldType.IsValueType && field.FieldType != typeof(String))
- {
- //不符合條件的字段,直接忽略,避免報錯。
- if ((field.FieldType.IsArray && (field.FieldType.GetArrayRank() > 1 || (!(tmptype = field.FieldType.GetElementType()).IsValueType && tmptype != typeof(String) && tmptype.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null) == null))) ||
- (!field.FieldType.IsArray && field.FieldType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null) == null))
- break;
- il.Emit(OpCodes.Ldloc_1);
- il.Emit(OpCodes.Ldloc_0);
- il.Emit(OpCodes.Ldfld, field);
- il.Emit(OpCodes.Ldarg_1);
- il.EmitCall(OpCodes.Call, typeof(ObjectCopy).GetMethod("CopyImpl", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(field.FieldType), null);
- il.Emit(OpCodes.Stfld, field);
- }
- else
- {
- il.Emit(OpCodes.Ldloc_1);
- il.Emit(OpCodes.Ldloc_0);
- il.Emit(OpCodes.Ldfld, field);
- il.Emit(OpCodes.Stfld, field);
- }
- }
- for (type = type.BaseType; type != null && type != typeof(object); type = type.BaseType)
- {
- //只須要查找基類的私有成員,共有或受保護的在派生類中直接被複制過了。
- fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance).ToList();
- foreach (var field in fields)
- {
- if (!field.FieldType.IsValueType && field.FieldType != typeof(String))
- {
- //不符合條件的字段,直接忽略,避免報錯。
- if ((field.FieldType.IsArray && (field.FieldType.GetArrayRank() > 1 || (!(tmptype = field.FieldType.GetElementType()).IsValueType && tmptype != typeof(String) && tmptype.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null) == null))) ||
- (!field.FieldType.IsArray && field.FieldType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null) == null))
- break;
- il.Emit(OpCodes.Ldloc_1);
- il.Emit(OpCodes.Ldloc_0);
- il.Emit(OpCodes.Ldfld, field);
- il.Emit(OpCodes.Ldarg_1);
- il.EmitCall(OpCodes.Call, typeof(ObjectCopy).GetMethod("CopyImpl", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(field.FieldType), null);
- il.Emit(OpCodes.Stfld, field);
- }
- else
- {
- il.Emit(OpCodes.Ldloc_1);
- il.Emit(OpCodes.Ldloc_0);
- il.Emit(OpCodes.Ldfld, field);
- il.Emit(OpCodes.Stfld, field);
- }
- }
- }
- }
- else
- {
- Type arraytype = type.GetElementType();
- var i = il.DeclareLocal(typeof(int));
- var lb1 = il.DefineLabel();
- var lb2 = il.DefineLabel();
- il.Emit(OpCodes.Ldarg_0);
- il.Emit(OpCodes.Castclass, type);
- il.Emit(OpCodes.Dup);
- il.Emit(OpCodes.Stloc_0);
- il.Emit(OpCodes.Ldlen);
- il.Emit(OpCodes.Dup);
- il.Emit(OpCodes.Ldc_I4_1);
- il.Emit(OpCodes.Sub);
- il.Emit(OpCodes.Stloc, i);
- il.Emit(OpCodes.Ldarg_2);
- il.Emit(OpCodes.Castclass, type);
- il.Emit(OpCodes.Dup);
- il.Emit(OpCodes.Stloc_1);
- il.Emit(OpCodes.Ldloc, i);
- il.Emit(OpCodes.Br, lb1);
- il.MarkLabel(lb2);
- il.Emit(OpCodes.Dup);
- il.Emit(OpCodes.Ldloc, i);
- il.Emit(OpCodes.Ldloc_0);
- il.Emit(OpCodes.Ldloc, i);
- il.Emit(OpCodes.Ldelem, arraytype);
- if (!arraytype.IsValueType && arraytype != typeof(String))
- {
- il.EmitCall(OpCodes.Call, typeof(ObjectCopy).GetMethod("CopyImpl", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(arraytype), null);
- }
- il.Emit(OpCodes.Stelem, arraytype);
- il.Emit(OpCodes.Ldloc, i);
- il.Emit(OpCodes.Ldc_I4_1);
- il.Emit(OpCodes.Sub);
- il.Emit(OpCodes.Dup);
- il.Emit(OpCodes.Stloc, i);
- il.MarkLabel(lb1);
- il.Emit(OpCodes.Ldc_I4_0);
- il.Emit(OpCodes.Clt);
- il.Emit(OpCodes.Brfalse, lb2);
- }
- il.Emit(OpCodes.Ret);
-
-
- return (Action<object, Dictionary<Identity, object>, object>)dm.CreateDelegate(typeof(Action<object, Dictionary<Identity, object>, object>));
- }
-
-
- static T CopyImpl<T>(T source, Dictionary<Identity, object> objects) where T : class
- {
- //爲空則直接返回null
- if (source == null)
- return null;
-
-
- Type type = source.GetType();
- Identity id = new Identity(source.GetHashCode(), type.TypeHandle);
- object result;
- //若是發現曾經複製過,用以前的,從而中止遞歸複製。
- if (!objects.TryGetValue(id, out result))
- {
- //最後查找對象的複製方法,若是不存在,建立新的。
- Func<object, Dictionary<Identity, object>, object> method;
- if (!methods1.TryGetValue(type, out method))
- {
- method = CreateCloneMethod1(type, objects);
- methods1.Add(type, method);
- }
- result = method(source, objects);
- }
- return (T)result;
- }
-
-
-
-
- /// <summary>
- /// 建立對象深度複製的副本
- /// </summary>
- public static T ToObjectCopy<T>(this T source) where T : class
- {
- Type type = source.GetType();
- Dictionary<Identity, object> objects = new Dictionary<Identity, object>();//存放內嵌引用類型的複製鏈,避免構成一個環。
- Func<object, Dictionary<Identity, object>, object> method;
- if (!methods1.TryGetValue(type, out method))
- {
- method = CreateCloneMethod1(type, objects);
- methods1.Add(type, method);
- }
- return (T)method(source, objects);
- }
-
-
-
-
- /// <summary>
- /// 將source對象的全部屬性複製到target對象中,深度複製
- /// </summary>
- public static void ObjectCopyTo<T>(this T source, T target) where T : class
- {
- if (target == null)
- throw new Exception("將要複製的目標未初始化");
- Type type = source.GetType();
- if (type != target.GetType())
- throw new Exception("要複製的對象類型不一樣,沒法複製");
- Dictionary<Identity, object> objects = new Dictionary<Identity, object>();//存放內嵌引用類型的複製鏈,避免構成一個環。
- objects.Add(new Identity(source.GetHashCode(), type.TypeHandle), source);
- Action<object, Dictionary<Identity, object>, object> method;
- if (!methods2.TryGetValue(type, out method))
- {
- method = CreateCloneMethod2(type, objects);
- methods2.Add(type, method);
- }
- method(source, objects, target);
- }
- }
- }
花了很多精力研究的最高效的通用方法,目前能支持任何帶無參數的構造函數的類的深拷貝,一元數組的深拷貝,數組和類的循環嵌套深拷貝,雙向鏈表結構 的類型對象深拷貝,進行對象拷貝過程當中,未判斷任何附加特性,所以可序列化標誌對其無效,即便不可序列化的對象,也能夠進行深拷貝。 數據庫
該方法是最基礎的方法,若是須要高級應用,能夠自定義特性(Attribute)進行忽略某些字段。 數組
該方法最多用途就是在數據庫的實體對象的賦值上面,操做一個臨時對象(複製出來),若是中途放棄改動,則直接丟棄對象,不影響原先的對象,不然可將對象複製回去。 緩存