Analysis on C # Deep copy and light copy

Source: Internet
Author: User
1. Deep copy and light copy Copy is usually referred to as copy or clone. Copying an object is a new object that is "identical" from an existing object. Although all objects are replication objects, the new objects copied by different replication methods are not exactly the same, and there are some differences within the objects. There are two common copy methods: Deep copy and shallow copy. What is the difference between them? In msdn, the clone method of the iclone interface is described as follows: In Deep replicas, all objects are duplicated, while in superficial replicas, only top-level objects are duplicated, and the objects below the top level include references. It can be seen that The difference is whether sub-objects are copied. How can this be understood? Below I use Code To verify the difference between the two. First, define two types: Student and classroom. The student type includes classroom, and enable these two types to implement the custom deep copy interface (ideepcopy) respectively) and ishallowcopy ). The class diagram is as follows:

The definition code is as follows: Define code

  ///     <Summary> 
/// Deep copy Interface
/// </Summary>
Interface Ideepcopy
{
Object Deepcopy ();
}

/// <Summary>
/// Shallow copy Interface
/// </Summary>
Interface Ishallowcopy
{
Object Shallowcopy ();
}

/// <Summary>
/// Classroom Information
/// </Summary>
Class Classroom: ideepcopy, ishallowcopy
{
Public Int Roomid = 1 ;
Public String Roomname = " Room1 " ;

Public Override String Tostring ()
{
Return " Roomid = " + Roomid + " \ Troomname = " + Roomname;
}
Public Object Deepcopy ()
{
Classroom R = New Classroom ();
R. roomid = This . Roomid;
R. roomname = This . Roomname;
Return R;
}
Public Object Shallowcopy ()
{
// Directly use the built-in shallow COPY method to return data
Return This . Memberwiseclone ();
}
}

Class Student: ideepcopy, ishallowcopy
{
// To simplify the process, use the public field
Public String Name;
Public Int Age;
// Custom type. Assume that each student has only one classroom.
Public Classroom room = New Classroom ();

Public Student ()
{
}
Public Student ( String Name, Int Age)
{
This . Name = Name;
This . Age = Age;
}
Public Object Deepcopy ()
{
Student s = New Student ();
S. Name = This . Name;
S. Age = This . Age;
S. Room = (Classroom) This . Room. deepcopy ();
Return S;
}
Public Object Shallowcopy ()
{
Return This . Memberwiseclone ();
}

Public Override String Tostring ()
{
Return " Name: " + Name + " \ Tage: " + Age + " \ T " + Room. tostring ();
}

}

 

Test code:

 

Test code

  Student S1 =     New  Student (  "  Vivi  "  ,  28  );
Console. writeline ( " S1 = [ " + S1 + " ] " );
Student S2 = (Student) s1.shallowcopy ();
// Student S2 = (student) s1.deepcopy ();
Console. writeline ( " S2 = [ " + S2 + " ] " ); // S2 and S1 share the same content.
Console. writeline ( " ----------------------------- " );
// Modify S2 content
S2.name = " Tianyue " ;
S2.age = 25 ;
S2.room. roomid = 2 ;
S2.room. roomname = " Room2 " ;
Console. writeline ( " S1 = [ " + S1 + " ] " );
Console. writeline ( " S2 = [ " + S2 + " ] " ); // Print two objects again to compare
Console. Readline ();

 

 

Running result: a. shallowcopys1 = [name: Vivi Age: 28 roomid = 1 roomname = room1]
S2 = [name: Vivi Age: 28 roomid = 1 roomname = room1]
------------------------------------------------------------- S1 = [name: Vivi Age: 28 roomid = 2 roomname = room2]
S2 = [name: tianyue age: 25 roomid = 2 roomname = room2] B. deepcopys1 = [name: Vivi Age: 28 roomid = 1 roomname = room1]
S2 = [name: Vivi Age: 28 roomid = 1 roomname = room1]
-----------------------------
S1 = [name: Vivi Age: 28 roomid = 1 roomname = room1]
S2 = [name: tianyue age: 25 roomid = 2 roomname = room2] from the above results, we can see that during deep copy, the two objects are completely "separated" and change one of them, it does not affect the other object. During the shortest copy, the two objects are not completely "separated". Changing the content of the top-level object does not affect the other object, but changes the content of the sub-object, the two objects are modified at the same time. The difference is determined by the replication memory or the replication pointer when the sub-object is copied. Deep copy re-allocates a memory space for the sub-object and copies the content. The light copy only points the pointer to the original sub-object. As follows: 2. Copying and assigning values In most object-oriented language assignment operations, a reference is passed, that is, the pointer address of the object is changed, and the memory is not copied and no replication operation is performed. We can see that the difference between the shallow copy operation and the value assignment operation is Whether the top-level object is copied or not. Of course, there are some exceptions, such as assignment operator in the type definition, or some type conventions passing by value, just like struct and enumeration types in C. The assignment operation is as follows: Based on. net reflection mechanism, previously written a general serialization method, now can be taken, first serialized, and then deserialized back, that is, a deep copy, the sample code is as follows: Deep copy sample code

    # Region  Icloneable members  

/// <Summary>
/// The replication here is a deep copy. in implementation, serialization and deserialization are used to simplify the process.
/// </Summary>
/// <Returns> Deep copy object </Returns>
Public Object Clone ()
{
Student Stu = New Student ();
Xmlstoragehelper helper = New Xmlstoragehelper ();
String Strxml = Helper. converttostring ( This );
Helper. loadfromstring (STU, strxml ); // Assign values from XML strings

Return Stu;
}

# Endregion
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.