Direct Copy of the reference type: There are two references in the memory, but there is only one copy of the real data. The two references point to the same real data.
Shallow copy: if the field is of the value type, perform a one-on-one copy of the field. If the field is of the work type, copy the referenced object without copying the referenced object.
Deep copy: Completely generates different objects. Fields in each object (value type or reference type) occupy different locations in the memory.
Code:
Code
Public class Resume: ICloneable
{
Private int age;
Private string name;
Private WorkExperice work;
Public Resume ()
{
Work = new WorkExperice ();
}
Public void SetInfo (int age, string name, string company)
{
This. age = age;
This. name = name;
Work. company = company;
}
Public void Display ()
{
Console. WriteLine ("{0 }:{ 1}, {2}", name, age, work. company );
}
# Region ICloneable Members
// Shallow copy
Public object Clone ()
{
Return this. MemberwiseClone ();
}
# Endregion
// Deep copy
Public object Copy ()
{
Resume res = new Resume ();
Res. age = this. age;
Res. name = this. name;
Res. work = (WorkExperice) work. Clone ();
Return res;
}
}
Public class WorkExperice: ICloneable
{
Public string company;
# Region ICloneable Members
Public object Clone ()
{
Return this. MemberwiseClone ();
}
# Endregion
}
Client code:
Code
# Direct copy of region reference type
// There are two references in the memory, but there is only one actual data, and the two references point to the same real data
Resume ResumeA = new Resume ();
ResumeA. SetInfo (18, "EngineA", "CompanyA ");
Resume ResumeB = ResumeA;
ResumeB. SetInfo (19, "EngineB", "CompanyB ");
ResumeA. Display ();
ResumeB. Display ();
// Expected result:
// EngineB: 19, CompanyB
// EngineB: 19, CompanyB
# Endregion
# Region shallow copy
// If the field is of the value type, perform a one-on-one copy of the field. If the field is of the work type, copy the referenced object without copying the referenced object.
Resume ResumeC = new Resume ();
ResumeC. SetInfo (20, "EngineC", "CompanyC ");
Resume ResumeD = (Resume) ResumeC. Clone ();
ResumeD. SetInfo (21, "EngineD", "CompanyD ");
ResumeC. Display ();
ResumeD. Display ();
// Expected result:
// EngineC: 20, CompanyD
// EngineD: 21, CompanyD
# Endregion
# Region deep copy
// Completely generate different objects. Fields in each object (value type or reference type) occupy different locations in the memory.
Resume ResumeE = new Resume ();
ResumeE. SetInfo (22, "EngineE", "CompanyE ");
Resume ResumeF = (Resume) ResumeE. Clone ();
ResumeF. SetInfo (23, "EngineF", "CompanyF ");
ResumeE. Display ();
ResumeF. Display ();
// Expected result:
// EngineE: 22, CompanyE
// EngineF: 23, CompanyF
# Endregion