C # Shallow copy and deep copy instance parsing

Source: Internet
Author: User
In some cases, we need to read the data from the database to populate the object or read the file from the hard disk to populate the object, but this is relatively time consuming. That's when we think of a copy of the object. In this paper, the use of C # shallow copy and deep copy is resolved in the form of instance. Specific as follows:

One, shallow copy

1. What is a "shallow copy":

When copying against an object, the value type member of the object is copied itself, and for the object's reference type member, only the object reference is copied, which points to the object instance on the managed heap.

2. There is an object that contains the class member of the reference type and the struct member of the value type

Cinema contains a reference type member of the class and value type member film.

public class room{public  int _maxseat;   Public Guest (int maxseat)  {    this._maxseat = maxseat;  }} public struct film{public  string _name;   Public Film (string name)  {    this._name = name;  }} The public class cinema{the public  _room;  Public Film _film;   Public Cinema (Film Film)  {    this._room = guest;    this._film = film;  }   public Object Clone ()  {    return memberwiseclone ();//apply shallow copy To reference type  }}

3. Test the effect after copying

① prints the values of the previous value type and the reference type member of the original object copy
② copies the original object, prints the value of the copied object value type and the reference type member
③ change the value of the original object, printing the value of the original object and the value of the reference type member again
④ duplicate values for object value types and reference type members

static void Main (string[] args) {  room1 = new);  Film film1 = new Film ("Homeland Defense");  Cinema cinema1 = new Cinema (room1, film1);  Cinema cinema2 = (cinema) cinema1. Clone ();  Console.WriteLine ("The struct member has a field value of {0} before the copy, the field value of the reference type member is {1}", cinema1._film._name,cinema1._room._maxseat);   Console.WriteLine ("After the copy, the field value of the new struct member is {0}, the field value of the reference type member is {1}", Cinema2._film._name, cinema2._room._maxseat);   The field value of the reference type before modifying the copy  Cinema1._film._name = "Need for Speed";  Cinema1._room._maxseat = n;   Console.WriteLine ("After modification, the struct member's field value is {0}, the field value of the reference type member is {1}", Cinema1._film._name, cinema1._room._maxseat);  Console.WriteLine ("The new struct member has a field value of {0} after the modification, the field value of the reference type member is {1}", Cinema2._film._name, cinema2._room._maxseat);   Console.readkey ();}

Analysis:

A shallow copy key is an object reference to a reference type that points to an object instance on the managed heap. Changing the value of the original corresponding reference type affects the copied object.

Second, deep copy

1. What is a "deep copy"?

The object pointed to by the reference member is also copied, the data contained in the original object instance is assigned on the managed heap, and a new object instance is created on the managed heap.

2. Deep copy by copying each member of the object

public Object Clone () {The "guest")  = new ();  Room._maxseat = this._room._maxseat;//Copy the value of the current reference type member to the new object  Film Film = this._film;//value type Direct assignment  cinema cinema = new Cinema (guest, film);  return cinema;}

3. Deep copy can also be serialized and deserialized

public Object Clone1 () {  BinaryFormatter bf = new BinaryFormatter ();  MemoryStream ms = new MemoryStream ();  Bf. Serialize (MS, this); Copy to the stream in  Ms. Position = 0;  Return (BF. Deserialize (ms));}

4. Use serialization and deserialization of deep copies, but must put all classes on [Serializable], the test code is as follows:

[serializable]public class room{public int _maxseat;  Public Guest () {} public (int maxseat) {this._maxseat = Maxseat;   }} [serializable]public struct film{public string _name;  Public Film (string name) {this._name = name;  }} [Serializable]public class cinema{public _room;   Public Film _film;    Public Cinema (Film Film) {this._room = guest;  This._film = film; }//Shallow copy//public Object Clone ()//{//Return MemberwiseClone ();//apply shallow copy To reference type////Deep copy replicate to each object member public OBJEC    T Clone () {The "guest") = new (); Room._maxseat = this._room._maxseat;//Copy the value of the current reference type member to the new object Film Film = this._film;    The value type is directly assigned to cinema cinema = new Cinema (film);  return cinema;    }//using serialization and deserialization to replicate public object Clone1 () {BinaryFormatter BF = new BinaryFormatter ();    MemoryStream ms = new MemoryStream (); Bf. Serialize (MS, this); Copy to the stream in Ms.    Position = 0; Return (BF.  Deserialize (ms)); }}

5. Test the effect after copying

① prints the values of the previous value type and the reference type member of the original object copy
② copies the original object, prints the value of the copied object value type and the reference type member
③ change the value of the original object, printing the value of the original object and the value of the reference type member again
④ duplicate values for object value types and reference type members

static void Main (string[] args)   {     room1 = new);     Film film1 = new Film ("Homeland Defense");     Cinema cinema1 = new Cinema (room1, film1);     Cinema cinema2 = (cinema) cinema1. Clone1 ();     Console.WriteLine ("The struct member has a field value of {0} before the copy, the field value of the reference type member is {1}", cinema1._film._name,cinema1._room._maxseat);      Console.WriteLine ("After the copy, the field value of the new struct member is {0}, the field value of the reference type member is {1}", Cinema2._film._name, cinema2._room._maxseat);      The field value of the reference type before modifying the copy     Cinema1._film._name = "Need for Speed";     Cinema1._room._maxseat = n;      Console.WriteLine ("After modification, the struct member's field value is {0}, the field value of the reference type member is {1}", Cinema1._film._name, cinema1._room._maxseat);     Console.WriteLine ("The new struct member has a field value of {0} after the modification, the field value of the reference type member is {1}", Cinema2._film._name, cinema2._room._maxseat);      Console.readkey ();   }

Results:

Analysis:

After a deep copy, the reference members of two objects are detached, and changing the value of the member of the original object reference type does not affect the value of the reference type member of the copied object.

Related Article

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.