We know that objects are divided into reference types and value types.
Shortest: copy an existing object and point the reference type to the same memory block. (string is the most special object. Here we use it as the value type first)
public class User { public int Age { get; set; } public string UserName { get; set; } public List<string> List { get; set; } public User ShallowCopy() { return this.MemberwiseClone() as User; } } class Program { static void Main(string[] args) { var user = new User(); user.List = new List<string>(); user.Age = 1; user.UserName = "lisi"; user.List.Add("lst1"); var cloneUser = user.ShallowCopy(); Console.WriteLine(user.List.Count()); Console.WriteLine(cloneUser.UserName); Console.WriteLine(user.Age); cloneUser.Age = 2; cloneUser.UserName = "zhangsan"; cloneUser.List.Add("lst2"); Console.WriteLine(user.List.Count()); Console.WriteLine(cloneUser.UserName); Console.WriteLine(user.Age); Console.ReadKey(); } }
Shallow copy code
The output values are:
1 (user. List. Count (), which indicates the reference type. Let's look at the output below)
Lisi
1
2 (Here we add a value after cloning, and we say they point to the same memory block, so here is 2)
Zhangsan
1
Supplement:
Some fields in an object are of the value type and some are of the reference type. For a value type field, its value is a simple value, and for a reference type, its value is an address.
During the replication process, all the value fields and reference fields (both non-static fields) of the object are copied to obtain the value and address of the object.
That is, when the variable in the address pointed to by the reference field of an object changes, the reference field in all the shortest copy objects will change.
Deep clone: copy an existing object and direct the reference type to another memory block (changing any value of the cloned object will not affect other values)
public class User { public int Age { get; set; } public string UserName { get; set; } public List<string> List { get; set; } public User Clone() { return new User() { Age = this.Age, UserName = this.UserName, List = new List<string>() { this.List[0] } }; } } class Program { static void Main(string[] args) { var user = new User(); user.List = new List<string>(); user.Age = 1; user.UserName = "lisi"; user.List.Add("lst1"); var cloneUser = user.Clone(); cloneUser.Age = 2; cloneUser.UserName = "zhangsan"; cloneUser.List[0] = "updatedlist"; Console.WriteLine(user.List[0]); Console.WriteLine(user.UserName); Console.WriteLine(user.Age); Console.ReadKey(); } }
View code
The output value is:
Lst1
Lisi
1
Note:
All reference types are deeply cloned.