Here is a small series to bring you a C # using reflection to implement the deep copy of the object method. Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.
Implementation method
Copying sub-objects one at a time is very labor-intensive, and if the sub-object is a reference type, you also need to consider whether to make further deep copies of the child objects.
In practice, if a class has dozens of sub-objects, copying them is tedious and time-consuming for developers.
So the reflection mechanism is used to implement.
However, if it is a service-side operation, it is recommended to implement it manually.
After all, the reflection mechanism is more efficient than writing directly.
Code:
public static class Deepcopyhelper {public static object Copy (This object obj) {object targetdeepcopyobj; Type TargetType = obj. GetType (); Value type if (Targettype.isvaluetype = = true) {targetdeepcopyobj = obj; }//reference type else {targetdeepcopyobj = System.Activator.CreateInstance (TargetType); Create reference object system.reflection.memberinfo[] membercollection = obj. GetType (). GetMembers (); foreach (System.Reflection.MemberInfo member in membercollection) {if (member. MemberType = = System.Reflection.MemberTypes.Field) {System.Reflection.FieldInfo Field = (system.reflect Ion. FieldInfo) member; Object fieldvalue = field. GetValue (obj); if (Fieldvalue is icloneable) {field. SetValue (Targetdeepcopyobj, (Fieldvalue as ICloneable). Clone ()); } else {field. SetValue (Targetdeepcopyobj, Copy (Fieldvalue)); } } else if (member. MemberType = = System.Reflection.MemberTypes.Property) {System.Reflection.PropertyInfo MyProperty = (Sys Tem. Reflection.propertyinfo) member; MethodInfo info = Myproperty.getsetmethod (false); if (info! = null) {Object propertyvalue = myproperty.getvalue (obj, null); if (PropertyValue is icloneable) {Myproperty.setvalue (Targetdeepcopyobj, (PropertyValue as Iclo neable). Clone (), NULL); } else {Myproperty.setvalue (targetdeepcopyobj, Copy (PropertyValue), null); }}}}} return targetdeepcopyobj; } }