C # Implementation of replication and deep replication in a detailed way

Source: Internet
Author: User
The following small series for everyone to bring a C # replication and deep replication implementation 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.

The difference between a deep copy and a shallow copy is that a shallow copy duplicates only the value of a value type, whereas the object contained in the instance still points to the original instance.

 Class Program {[Serializable] public class Car {public string name;      Public Car (string name) {this.name = name;      }} [Serializable] public class Person:icloneable {public int id;      public string name;      public car car;        Public person () {} public person (int ID, string name, car car) {this.id = ID;        THIS.name = name;      This.car = car; The public Object Clone ()//implements the ICloneable interface to achieve a shallow copy. Shallow replication is not directly related to deep replication. Provides an external ability to create a shallow copy of itself {return this.      MemberwiseClone ();    }}//The instance to be copied must be serializable, including the other instances referenced by the instance must have the [Serializable] attribute added to the class definition. public static T copy<t> (t realobject) {using (Stream Objectstream = new MemoryStream ()) {//Exploit        System.Runtime.Serialization serialization and deserialization complete the replication of the referenced object IFormatter formatter = new BinaryFormatter (); Formatter.        Serialize (Objectstream, realobject);        Objectstream.seek (0, Seekorigin.begin); Return (T) formatter.      Deserialize (Objectstream);      }} static void Main (string[] args) {person P1 = new person (1, "Scott", New Car ("BMW"));      Console.WriteLine ("Original value: P1:id={0}----------->name={1}------>car={2}", P1.id, P1.name, p1.car.name); person P2 = copy<person> (p1); Clones an object person P3 = p1.      Clone () as person;//shallow copy Console.WriteLine ("Change the value of P1");      P1.id = 2;      P1.name = "Lacy";      P1.car.name = "Red Flag";      Console.WriteLine ("P1:id={0}----------->name={1}------>car={2}", P1.id, P1.name, p1.car.name);      Console.WriteLine ("Deep copy: p2:id={0}----------->name={1}------>car={2}", P2.id, P2.name, p2.car.name);      Console.WriteLine ("Shallow copy: p3:id={0}----------->name={1}------>car={2}", P3.id, P3.name, p3.car.name);    Console.readkey (); }

Operation Result:

One, the T in the List<t> object is the case of the value type (int type, etc.)

A list of value types can be copied directly using the following methods:

list<t> oldlist = new list<t> (); Oldlist.add (..); list<t> NewList = new list<t> (oldlist);

Second, the T in the List<t> object is the case of a reference type (for example, a custom entity class)

1. The list of reference types cannot be copied with the above methods, only the references to the objects in the list are copied, and can be copied with the following extension methods:

Static class Extensions  {public      static ilist<t> clone<t> (this ilist<t> listtoclone) where T: ICloneable      {          return Listtoclone.select (item = (T) item. Clone ()). ToList ();      }  <span style= "COLOR: #000000" > Of course the previous question is the list of objects to implement ICloneable interface </SPAN>}

2. Another way to make a deep copy of a reference object in a serialized manner, this method is the most reliable

public static T clone<t> (t realobject) {    using (Stream objectstream = new MemoryStream ())    {       //using System . Runtime.serialization serialization and deserialization complete the replication of the referenced object       iformatter formatter = new BinaryFormatter ();        Formatter. Serialize (Objectstream, realobject);        Objectstream.seek (0, seekorigin.begin);        Return (T) formatter. Deserialize (Objectstream);    } }

3. Using System.Xml.Serialization to realize serialization and deserialization

public static T clone<t> (t realobject) {       using (Stream stream=new MemoryStream ())      {        XmlSerializer Serializer = new XmlSerializer (typeof (T));        Serializer. Serialize (stream, realobject);        Stream. Seek (0, seekorigin.begin);        Return (T) serializer. Deserialize (stream);}      }
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.