<summary>///Object copy///</summary>//<param name= "obj" > Replicated Objects </param> <returns> New Object </returns> Private Object Copyojbect (object obj) {if (obj = = null) { return null; } 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) {//Copy field if (Membe R.membertype = = System.Reflection.MemberTypes.Field) {System.Reflection.FieldIn Fo field = (system.reflection.FieldInfo) member; Object fieldvalue = field. GetValue (obj); if (Fieldvalue is icloneable) {field. SetValue (Targetdeepcopyobj, (Fieldvalue as ICloneable). Clone ()); } else {field. SetValue (Targetdeepcopyobj, Copyojbect (Fieldvalue)); }}//Copy Property else if (member. MemberType = = System.Reflection.MemberTypes.Property) {System.Reflection.PropertyInfo MyProperty = (System.Reflection.PropertyInfo) member; MethodInfo info = Myproperty.getsetmethod (false); if (info! = null) {try {object propertyvalue = Myproperty.getv Alue (obj, null); if (PropertyValue is ICloneable) { Myproperty.setvalue (Targetdeepcopyobj, (PropertyValue as ICloneable). Clone (), NULL); } else {Myproperty.setvalue (targetdeepcopyobj, Copyojbe CT (propertyvalue), null); }} catch (System.Exception ex) {} }}}} return targetdeepcopyobj; }
Here is an answer on the StackOverflow:
public static T deepclone<t> (T obj) {using (var ms = new MemoryStream ()) { var formatter = new BinaryFormatter () ; Formatter. Serialize (MS, obj); Ms. Position = 0; Return (T) formatter. Deserialize (MS); }}
Notes:
Your class must is marked as [Serializable] in the order for the to work.
Your source file must include the following code:
Using System.Runtime.Serialization.Formatters.Binary;
Using System.IO;
For reference only.
I ' ve seen a few different approaches to this and I use a generic utility method as such:
C # deep copy