C # deep copy

Source: Internet
Author: User

<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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.