浅度复制:只是复制类的值类型字段和引用类型字段的引用
深度复制:即完全复制过来,不管里面的值类型字段还是引用类型字段,是构成一个全新的一模一样的对象。
代码:
1 public class PersonInfo
2 {
3 public string Name{get;set;}
4 public int Age{get;set;}
5 }
6 public class Person : ICloneable
7 {
8 public PersonInfo PersonInfo { get; set; }
9 public Person(PersonInfo personInfo)
10 {
11 this.PersonInfo = personInfo;
12 }
13
14 /// <summary>
15 /// 浅度克隆
16 /// </summary>
17 /// <returns></returns>
18 public Person ShallowClone()
19 {
20 return this.MemberwiseClone() as Person;
21 }
22
23 /// <summary>
24 /// 深度复制(实现ICloneable接口的方法)
25 /// </summary>
26 /// <returns></returns>
27 public object Clone()
28 {
29 PersonInfo perInf = new PersonInfo { Name = this.PersonInfo.Name, Age = this.PersonInfo.Age };
30 Person per = new Person(perInf);
31 return per;
32 }
33
34 /// <summary>
35 /// 第二种深度复制
36 /// </summary>
37 /// <returns></returns>
38 public Person DeepClone()
39 {
40 using (var ms = new MemoryStream())
41 {
42 var formatter = new BinaryFormatter();
43 formatter.Serialize(ms, this);
44 ms.Position = 0;
45 return (Person)formatter.Deserialize(ms);
46 }
47 }
48 }
引用:深度复制问题..当对象成员有很多引用成员,如何深度复制。
时间: 2024-10-08 14:17:51