Cloning objects are often encountered during the development process, sometimes need shallow cloning, sometimes need to deep cloning, the specific differences between them, and the implementation of the way there, summed up here.
There are several ways to implement deep cloning.
Manual
The code is as follows:
Manually copy var user2 = new User{id = user1. Id,name = new UserName {firstname= user1. Name.firstname,lastname= user1. Name.lastname}};
Reflection
The code is as follows:
1//Reflection 2 var User3 = user1. Copy () as User;
Extension methods:
1 public static class Deepcopyhelper 2 {3 publicly static object Copy (This object obj) 4 {5 Object target Deepcopyobj; 6 Type targetType = obj. GetType (); 7//value type 8 if (Targettype.isvaluetype = = true) 9 {targetdeepcopyobj = obj;11 }12//reference type ELSE14 {targetdeepcopyobj = System.Activator.CreateInstance (targetty PE); Create reference object system.reflection.memberinfo[] membercollection = obj. GetType (). GetMembers (); System.Reflection.MemberInfo member in membercollection) 19 {20 if (member. MemberType = = System.Reflection.MemberTypes.Field) {System.Reflection.FieldInfo F Ield = (System.Reflection.FieldInfo) member;23 Object fieldvalue = field. GetValue (obj); if (Fieldvalue is icloneable) . SetvAlue (Targetdeepcopyobj, (Fieldvalue as ICloneable). Clone ());}28 else29 {field. SetValue (Targetdeepcopyobj, Copy (Fieldvalue)),}32}34 else if (m Ember. MemberType = = System.Reflection.MemberTypes.Property) {System.Reflection.Property Info myproperty = (System.Reflection.PropertyInfo) member;37 MethodInfo info = Myproperty.getsetmethod ( FALSE) if (info! = null) The PropertyValue = M Yproperty.getvalue (obj, null); if (PropertyValue is icloneable) 42 {43 Myproperty.setvalue (Targetdeepcopyobj, (PropertyValue as ICloneable). Clone (), null),}45 else46 {47 Myproperty.setvalue (Targetdeepcopyobj, Copy (PropertyValue), null); 48}49 }50}52}53}54 return targetdeepcopyobj;55}56}
View Code
Serialization of
The code is as follows:
1//Serialization of 2 var user4 = user1. Deepclone ();
Extension methods:
1//<summary> 2//Deep clone 3///first serialization and re-serialization 4//</summary> 5//<typeparam name= "T" ></typeparam> 6//<param name= "obj" ></param> 7//<returns></returns> 8 public static T deepclone<t> (t His T obj) where T:class 9 {ten return obj! = null? obj. ToJson (). Fromjson<t> (): null;11}
View Code
Other expressions are also used.
Summarize:
Manual copy performance is best, but when you encounter very complex classes, the workload is great.
Serialization is simpler than reflection and serialization.