Reading Comprehension-C # shallow copy and deep copy:
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.
Deep copy, that is, the icloneable interface. icloneable can be used for deep copy and light copy.
Please refer to the following sentence.
Using System;
Using System. Collections. Generic;
Public Class Myclass
{
Class Instancea: icloneable
{
Public Int X;
Public Instanceb B;
Public Instancea () {}
Public Instancea ( Int X, instanceb B)
{
This. X=X;
This. B=B;
}
Object Icloneable. Clone ()
{
Return This. Clone ();
}
Public Instancea clone ()
{
Instancea = This . Memberwiseclone () As Instancea;
A. B = This . B. Copy ();
Return A; // Deep Replication
// Return (instancea) This. memberwiseclone (); // Light Replication
// Return new instancea (this. X, this. B ); // Use this can't get deep copy too ..
}
}
Class Instanceb
{
Public Int Y;
Public Instanceb copy ()
{
Return This. Memberwiseclone ()AsInstanceb;
}
}
Public Static Void Main ()
{
Instancea obj1 = New Instancea ();
Obj1.x = 1 ;
Obj1. B = New Instanceb ();
Obj1. B. Y = 2 ;
Instancea obj2 = Obj1.clone ();
Obj2.x = 3 ;
Obj2. B. Y = 4 ;
Console. writeline ( " Obj1.x is: {0} \ t obj1. B. Y = {1} " , Obj1.x, obj1. B. y );
Console. writeline ( " Obj2.x is: {0} \ t obj2. B. Y = {1} " , Obj2.x, obj2. B. y );
Console. Readline ();
}
}