C # copy (deep copy and light copy ),

Source: Internet
Author: User

C # copy (deep copy and light copy ),
Object. MemberwiseClone Method

Creates a superficial copy of the current Object.

protected Object MemberwiseClone()

The MemberwiseClone method creates a superficial copy by creating a new object and then copying the non-static fields of the current object to the new object. If the field is of the value type, perform a step-by-step copy on the field. If the field is of reference type, the referenced object is copied but not referenced. Therefore, the original object and its counterparts reference the same object.

For example, if object X references objects A and B, object B references objects C in turn. The child copy of X creates A new object X2, which also references objects A and B. In contrast, the deep copy of X creates A new object X2, which references the new objects A2 and B2 (copies of A and B respectively ). B2 references the new object C2, which is a copy of C. This example illustrates the differences between a replication operation and a replication operation.


There are many ways to implement deep replication, provided that the superficial replication operation is executed by the MemberwiseClone method but does not meet your needs.

These requirements include:

The following example demonstrates the MemberwiseClone method. It defines the ShallowCopy method, which calls the MemberwiseClone method to perform a superficial copy operation on the Person object. It also defines the DeepCopy Method for performing deep copy operations on the Person object.

using System;public class IdInfo{    public int IdNumber;    public IdInfo(int IdNumber)    {        this.IdNumber = IdNumber;    }}public class Person {    public int Age;    public string Name;    public IdInfo IdInfo;    public Person ShallowCopy()    {       return (Person)this.MemberwiseClone();    }    public Person DeepCopy()    {       Person other = (Person) this.MemberwiseClone();        other.IdInfo = new IdInfo(this.IdInfo.IdNumber);       return other;    }}public class Example{    public static void Main()    {        // Create an instance of Person and assign values to its fields.        Person p1 = new Person();        p1.Age = 42;        p1.Name = "Sam";        p1.IdInfo = new IdInfo(6565);        // Perform a shallow copy of p1 and assign it to p2.        Person p2 = (Person) p1.ShallowCopy();        // Display values of p1, p2        Console.WriteLine("Original values of p1 and p2:");        Console.WriteLine("   p1 instance values: ");        DisplayValues(p1);        Console.WriteLine("   p2 instance values:");        DisplayValues(p2);        // Change the value of p1 properties and display the values of p1 and p2.        p1.Age = 32;        p1.Name = "Frank";        p1.IdInfo.IdNumber = 7878;        Console.WriteLine("\nValues of p1 and p2 after changes to p1:");        Console.WriteLine("   p1 instance values: ");        DisplayValues(p1);        Console.WriteLine("   p2 instance values:");        DisplayValues(p2);        // Make a deep copy of p1 and assign it to p3.        Person p3 = p1.DeepCopy();        // Change the members of the p1 class to new values to show the deep copy.        p1.Name = "George";        p1.Age = 39;        p1.IdInfo.IdNumber = 8641;        Console.WriteLine("\nValues of p1 and p3 after changes to p1:");        Console.WriteLine("   p1 instance values: ");        DisplayValues(p1);        Console.WriteLine("   p3 instance values:");        DisplayValues(p3);    }    public static void DisplayValues(Person p)    {        Console.WriteLine("      Name: {0:s}, Age: {1:d}", p.Name, p.Age);        Console.WriteLine("      Value: {0:d}", p.IdInfo.IdNumber);    }}// The example displays the following output://       Original values of p1 and p2://          p1 instance values://             Name: Sam, Age: 42//             Value: 6565//          p2 instance values://             Name: Sam, Age: 42//             Value: 6565//       //       Values of p1 and p2 after changes to p1://          p1 instance values://             Name: Frank, Age: 32//             Value: 7878//          p2 instance values://             Name: Sam, Age: 42//             Value: 7878//       //       Values of p1 and p3 after changes to p1://          p1 instance values://             Name: George, Age: 39//             Value: 8641//          p3 instance values://             Name: Frank, Age: 32//             Value: 7878

To achieve deep replication, We must traverse graphs composed of mutually referenced objects and process the cyclic reference structure. This is undoubtedly very complicated. Fortunately, with the serialization and deserialization mechanisms of. Net, an object can be cloned in depth.

The principle is very simple. First, serialize the object to the memory stream. At this time, the state of the object referenced by the object is saved to the memory .. Net serialization mechanism will automatically handle the situation of loop reference. Then, status information in the memory stream is deserialized into a new object.

This completes the deep replication of an object. In the prototype design mode, CLONE is critical.

Using System; using System. IO; using System. runtime. serialization. formatters. binary; namespace CloneDemo {[Serializable] class DemoClass {public int I = 0; public int [] iArr = {1, 2, 3}; public DemoClass Clone1 () // shallow CLONE {return this. memberwiseClone () as DemoClass;} public DemoClass Clone2 () // deep clone {MemoryStream stream = new MemoryStream (); BinaryFormatter formatter = new BinaryFormatter (); formatter. serialize (stream, this); stream. position = 0; return formatter. deserialize (stream) as DemoClass;} class Program {static void Main (string [] args) {DemoClass a = new DemoClass ();. I = 10;. iArr = new int [] {8, 9, 10}; DemoClass B =. clone1 (); DemoClass c =. clone2 (); // change iArr [0] of object a, resulting in iArr [0] of object B also changing, and c will not change. iArr [0] = 88; Console. writeLine ("MemberwiseClone"); Console. writeLine (B. i); foreach (var item in B. iArr) {Console. writeLine (item);} Console. writeLine ("Clone2"); Console. writeLine (c. i); foreach (var item in c. iArr) {Console. writeLine (item);} Console. readLine ();}}}

Reference: http://www.cnblogs.com/zhangji/archive/2011/02/23/1961897.html

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.