Introduction
There are two types of variables in C #, one is the value type variable, one is the reference type variable, for the value type variable, the deep copy and the front copy are implemented by the assignment operation symbol (=), the effect is consistent, and the field of the value type in the object is copied to the new object. This is easy to understand. This paper focuses on the copying mechanism and implementation of reference type variables.
There are two types of copy operations for reference type objects in C #:
Shallow copy (shadow clone/shallow copy): Only the value Type field of the object is copied, and the reference type of the object still belongs to the original reference.
Deep copy (depth cloning): Not only the value Type field of the object is copied, but also the objects in the original object are copied. That is, it is entirely a new object.
The difference between a shallow copy and a deep copy: a shallow copy is a copy of a field of a numeric type in an object to a new object, whereas a reference field in an object refers to copying one of its references to the target object.
Note: String types are somewhat special, and for shallow copies, class value type objects are processed.
The implementation of shallow copy
Using the object class MemberwiseClone implementation
MemberwiseClone: Creates a shallow copy of the current Object.
The MemberwiseClone method creates a shallow copy by creating a new object and then copying the non-static field of the current object to the new object. If the field is a value type, a bitwise copy is performed on the field. If the field is a reference type, the reference is copied but not the referenced object, so the original object and its copy refer to the same object.
The code implementation is as follows:
public class Person
{
public int Age { get; set; }
public string Address { get; set; }
public Name Name { get; set; }
public object Clone()
{
return this.MemberwiseClone();
}
}
public class Name
{
public Name(string frisName,string lastName)
{
FristName = frisName;
LastName = lastName;
}
public string FristName { get; set; }
public string LastName { get; set; }
}