On deep copy and shallow copy under. NET Platform

Source: Internet
Author: User
Tags shallow copy tostring

  in the. NET class Library, object cloning exists widely in various types of implementations, and all types that implement the ICloneable interface have the ability to clone their object instances. So deep and shallow copies of this article are also based on the implementation of the ICloneable interface

Basic concept:   Shallow copy: Refers to the object's fields are copied, and the fields referenced by the object will not be copied, copy objects and the original object is only the reference name is different, but they share an entity. Changes to any one object affect the other. Most of the reference types implement a shallow copy, and the assignment between reference type objects is to copy a copy of an object reference address, and the object instance pointing to is still the same.   Deep copy: The fragment of the object is copied, and the object referenced by the field is also copied. Deep copy creates the structure of the entire source object, the Copy object and the original object are independent of each other, do not share any instance data, and modifying an object does not affect the other object. The assignment operation between value types performs a deep copy.   Basic concept of reference code:   Code as follows: Class program     {        static void Main (string[] args) & nbsp       {            Student S1 = new Student ("Li",);              //Light copy             Student s2 = s1;             S2. Age = 27;             S1. Showinfo ();//li ' s is              /deep copy           &NBS P int i = 12;             Int j = i;             j = 22;             ConSole. WriteLine (i);//12               console.read ();                   class Student     {      &NBS P public string Name;         public int age;           public Student (string name, int age)         {            NAME = name;             age = age;        }           public void Showinfo ()         {&nbs P           Console.WriteLine ("{0} ' s age are {1}", Name, age);        }     {    analysis:   In the above example, the instance s2 a shallow copy of S1, changes the age field in S2, and then affects the age field in the instance S1.   Deep copies are simply assignments between value types, and changes to "J" do not change the value of "I".   Deep Copy implementation: Code as follows: public Object Clone () {return this. MemberwiseClone (); }     MemberwiseClone: Create a shallow copy of the table. The procedure is to create a new object and then the current objectis copied to the new object by a non-static field. If the field is a value type, a bitwise copy is performed on the field, and if the field is a reference type, the reference is copied but the reference object is not copied.   Reference code:     Code as follows: Class program     {        static void Main (string[] args)         {            ClassA CA = new ClassA ()       &NB Sp     Ca.value = 88;             ClassA CA2 = new ClassA ();             CA2 = (ClassA) ca. Clone ();             ca2.value = 99;             Console.WriteLine (ca.value + "-----" + ca2.value)//88---,               CLASSB cb = new CLASSB ();             CB. Member.value = 13;               CLASSB CB2 = (CLASSB) cb. Clone ();             CB2. Member.value = 7;             Console.WriteLine (CB. Member.value.ToStrING () + "------" + CB2. Member.value.ToString ())//Light copy: 7---7       DEEP copy:----7              & nbsp           console.read ();        }           public class classa:icloneable     {        public int value = 0;           public Object Clone ()         {            return this. MemberwiseClone ();        }           public class classb:icloneable     {        Public ClassA member = new ClassA ();           public Object Clone ()         {          & nbsp  //Light copy             return this. MemberwiseClone ();              //Deep copy             CLASSB obj = new ClassB ();             obj. member = (ClassA) member.clone ();             return obj;        }     {      analysis:   In the example above, Ca2 replicates the CA object and implements a deep copy. The result is as shown in the code: the change in the value Type field in Ca2 does not affect the fields in the CA.   in class CLASSB, reference type member members, if implemented using the Clone method in ClassA, only a shallow copy is realized, as can be seen in the reference code above: The change to CB2 's membership affects CB. However, when using the deep copy in the reference code, the change to member of CB2 will not affect CB.   Find a comprehensive example on the Internet, there is a contrast to explain the depth of the copy:   instance 1:   Code as follows: public class sex:icloneable      {  &NBSP ;     private string _psex;         public string psex         {            Set {_psex = value;}             get {return _psex;}        }          //public Object Clone ()        //{       //   return this. MemberwiseclonE ();        //}    }       public class person:icloneable     {&nbs P         private Sex Sex = new Sex ();         public int aa = 3;           public string psex         {          &NB Sp set {sex. Psex = value; }             sex. Psex; {       }         private string _pname;         public string pname         {            SE t {this._pname = value;}             get {return this._pname;}       &NBS P }           public void Showpersoninfo ()         {      &NBSP ;     Console.WriteLine ("-------------------------");             Console.WriteLine ("Name:{0} Sex:{1}", _pname, This.psex);             Console.WriteLine ("-------------------------");             Console.WriteLine (THIS.AA);        }        /light copy         public Object Clone ()   & nbsp     {            return this. MemberwiseClone ();        }        /deep copy         public Object Deepclone () &nbs P       {     ,       person NEWP = new person ();         & nbsp   Newp.pname = This._pname;             newp.psex = This.psex;             return NEWP;        }     {      class program     {      &NBS P static void Main (string[) args)         {            Console.WriteLine ("Original object:");             person p = new person ();             P.pname = "Lee";             p.psex = "male";               p.showpersoninfo ()//original object: Lee Man 3           &NBSP ;  //Light copy                     person copy = (person) p.clone ();            //Deep copy             dcopy = (person) p.deepclo NE ();               Console.WriteLine ("Modified original object:");             P.pname = "Zhao";             P.psex = "female";             P.AA = 1;             p.showpersoninfo ()//zhao Women 1       &NBSp       Console.WriteLine ("Modified Shallow Copy object:");             copy. Showpersoninfo ();//lee 3               Console.WriteLine ("Modified Deep Copy object:");             dcopy. Showpersoninfo ();//lee man 3               Console.WriteLine ("Direct Copy object:");             person PP = p;             PP. Showpersoninfo ();//zhao Women 1               console.readline ();        }     {      analysis:   First of all, it should be noted that in the class sex in the example above, the addition of the Clone method and the absence of the result of the operation in the instance have no effect.   person, reference type but is a string type pname field, reference type Psex field, value type AA.   Initial value: Lee 3   (first deep copy)   modified value: Zhao 1   Shallow copy value: Lee female 3   Depth copy value: Lee man 3   Direct copy value: Zhaoju 1   knot Fruit: The above can be said to the deep copy often encountered several types to make a summary and comparison, I believe that after some understanding can learn some knowledge.   Example 2:     Code as follows: Class program     {      &NBsp static void Main (string[] args)         {            int[] numbers = { 2, 3, 4, 5};             int[] numberscopy = new INT[5];             numbers. CopyTo (numberscopy, 0);             numberscopy[2] = 0;               int[] numbers1 = {2, 3, 4, 5};             int[] numbersClone1 = (int[]) numbers1. Clone ();             numbersclone1[2] = 0;               Console.Write (numbers[2] + "---" + numberscopy[2])//4---0             Console.Write (numbers1[2] + "---" + numbersclone1[2])//4--0         &NBSP ;      //array replication refers to the same address             int[] Numbers2 = {2, 3, 4, 5};             int[] Numbers2copy = numbers2;             numbers2copy[2] = 0;               Console.Write (numbers2[2])//0             Console.Write (numbers2copy[2]);//0               console.read ();        }    }     No analysis, serious understanding.

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.