C # Shallow cloning and deep cloning

Source: Internet
Author: User
Tags readline serialization

First, shallow cloning:

In a shallow clone, if the member variable of the prototype object is a value type, a copy is copied to the cloned object, and if the stereotype object's member variable is a reference type, the address of the referenced object is copied to the cloned object, that is, the prototype object and the member variable of the cloned object point to the same memory address. In simple terms, in a shallow clone, when an object is replicated, only the member variables of itself and the value type contained therein are replicated, and the member objects of the reference type are not replicated, as shown in the figure:

In C #, a shallow clone is implemented by implementing the Clone Method () of the ICloneable interface () to invoke the MemberwiseClone method:

    public class weeklylog:icloneable
    {public
        string Name {get; set;}
        Public Student Student {get; set;}

        public Object Clone ()
        {return this
            . MemberwiseClone ();
        }
    
    {public
        string address {get; set;}
    }
 static void Main (string[] args) {Weeklylog log1 = new Prototypetest.weeklylog
            (); Log1.
            Name = "Log1"; Log1.

            Student = new Prototypetest.student () {address = "Haidian"}; Weeklylog log2 = (weeklylog) log1. Clone ();//Invoke Shallow Clone method Console.WriteLine (Log1. Name);//log1 Console.WriteLine (log2. Name);//log1 Console.WriteLine (Log1. student.address);//haidian Console.WriteLine (log2. student.address);//haidian Console.WriteLine (object. ReferenceEquals (Log1, log2));//false log2. Name = "LOG2";//Modify the Name property of the cloned object Console.WriteLine (Log1. Name);//log1 Console.WriteLine (log2. Name);//log2 log2. student.address = "Chaoyang";//Modify the reference type of the cloned object Student the Address property Console.WriteLine (Log1. student.address);//chaoyang Console.WriteLine (log2.

        student.address);//chaoyang console.readline (); }

Second, deep cloning:

In a deep clone, whether the member variable of a prototype object is a value type or a reference type, a copy is copied to the cloned object, and a deep clone copies all the referenced objects of the prototype object to the cloned object. In simple terms, in a deep clone, in addition to the object itself being replicated, all the member variables contained in the object will also be copied, as shown in the figure:

In the C # language, if you need to implement deep cloning, you can do so through serialization (serialization). Serialization is the process of writing an object to a stream, and the object written to the stream is a copy of the original object, and the original object still exists in memory. A copy of a serialized implementation can replicate not only the object itself, but also the member objects it references, so that deep cloning can be achieved by serializing the object into a stream and then reading it out of the stream. It is important to note that the object whose class is capable of implementing the serialization must implement the Serializable interface, otherwise the serialization operation cannot be implemented. Below we use the deep cloning technology to achieve work weekly and attachment object replication, because the Attachment object and work weekly object are written to the stream, so two classes with serializable identity serializable:

 [Serializable] public class Weeklylog {public string Name {get; set;}

        Public Student Student {get; set;}
            Public Weeklylog Deepclone () {object obj = null;
            Serializes an object into an in-memory binary stream BinaryFormatter Inputformatter = new BinaryFormatter ();
            MemoryStream InputStream;
            using (InputStream = new MemoryStream ()) {inputformatter.serialize (InputStream, this); ////deserialize binary stream into object using (MemoryStream outputstream = new MemoryStream (Inputstream.toarray ())
                ) {BinaryFormatter Outputformatter = new BinaryFormatter ();
            obj = Outputformatter.deserialize (outputstream);
        Return (weeklylog) obj;

    } [Serializable] public class Student {public string address {get; set;} }
<pre name= "code" class= "CSharp" > Static void Main (string[) args) {Weeklylog log1 = new Proto
            Typetest.weeklylog (); Log1.
            Name = "Log1"; Log1.

            Student = new Prototypetest.student () {address = "Haidian"}; Weeklylog log2 = (weeklylog) log1. Deepclone ()//calls the deep cloning method Console.WriteLine (Log1. Name);//log1 Console.WriteLine (log2. Name);//log1 Console.WriteLine (Log1. student.address);//haidian Console.WriteLine (log2. student.address);//haidian Console.WriteLine (object. ReferenceEquals (Log1, log2));//false log2. Name = "LOG2";//Modify the Name property of the cloned object Console.WriteLine (Log1. Name);//log1 Console.WriteLine (log2. Name);//log2 log2. student.address = "Chaoyang";//Modify the reference type of the cloned object Student the Address property Console.WriteLine (Log1. student.address);//haidian Console.WriteLine (log2.

  student.address);//chaoyang console.readline ();      } 




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.