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? Next I will verify the difference between the two through code with sub-objects. 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:
/// <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 + "RoomName =" + 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
{
// Use the public field for simplicity
Public string Name;
Public int Age;
// Custom type. Assume that each Student has only one ClassRoom
Public ClassRoom Room = new ClassRoom ();