克隆物件在開發過程中經常會遇到,有些時候需要淺克隆,有些時候需要深克隆,具體它們之間有什麼區別,以及實現方式有哪些,在這裡總結一下。
實作深克隆有以下幾種方法。
程式碼如下:
//手动复制 var user2 = new User { Id = user1.Id, Name = new UserName { FirstName= user1.Name.FirstName, LastName= user1.Name.LastName } };
#
1 //反射2 var user3 = user1.Copy() as User;擴充法:
1 public static class DeepCopyHelper 2 { 3 public static object Copy(this object obj) 4 { 5 Object targetDeepCopyObj; 6 Type targetType = obj.GetType(); 7 //值类型 8 if (targetType.IsValueType == true) 9 {10 targetDeepCopyObj = obj;11 }12 //引用类型 13 else14 {15 targetDeepCopyObj = System.Activator.CreateInstance(targetType); //创建引用对象 16 System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();17 18 foreach (System.Reflection.MemberInfo member in memberCollection)19 {20 if (member.MemberType == System.Reflection.MemberTypes.Field)21 {22 System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;23 Object fieldValue = field.GetValue(obj);24 if (fieldValue is ICloneable)25 {26 field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());27 }28 else29 {30 field.SetValue(targetDeepCopyObj, Copy(fieldValue));31 }32 33 }34 else if (member.MemberType == System.Reflection.MemberTypes.Property)35 {36 System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;37 MethodInfo info = myProperty.GetSetMethod(false);38 if (info != null)39 {40 object propertyValue = myProperty.GetValue(obj, null);41 if (propertyValue is ICloneable)42 {43 myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);44 }45 else46 {47 myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null);48 }49 }50 51 }52 }53 }54 return targetDeepCopyObj;55 }56 }
程式碼如下:
1 //序列化2 var user4 = user1.DeepClone();
#
1 /// 631fb227578dfffda61e1fa4d04b7d25 2 /// 深克隆 3 /// 先序列化再反序列化 4 /// 039f3e95db2a684c7b74365531eb6044 5 /// d65706098b2250eee2f48a758c9680c88ed7e392d75469626ca6a252f320a704 6 /// 9eeacba56bab5a25cf1fbc370b62c92f8bb7487ae6a16a43571bc14c7fcf93c2 7 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 8 public static T DeepClone8742468051c85b06f0a0af9e3e506b5c(this T obj) where T : class 9 {10 return obj != null ? obj.ToJson().FromJson8742468051c85b06f0a0af9e3e506b5c() : null;11 }######View Code######### #######其它還有使用表達式。 ######總結:############手動複製效能最好,但是遇到很複雜的類別的時候,工作量很大。 ############反射和序列化比起來,序列化更簡單。 ############ ####
以上是複製物件的方法實例教程的詳細內容。更多資訊請關注PHP中文網其他相關文章!