c#中对象的深拷贝和浅拷贝
c#中的深拷贝和浅拷贝,首先说它们在内存堆中都是产生了一个新的对象,而不是只复制了引用,指向同一个对象。它们的不同之处在于,对象内部的引用类型拷贝(string类型除外,因为他有自己的特性)。
浅拷贝:对象内部引用类型只拷贝引用,实质上还是指向内存堆中同一个对象;
深拷贝:产生了新的对象,在内存堆中指向不同的对象。
下面是在c#中实现深拷贝和浅拷贝的代码:
1、首先定义2个类
电脑类
1 [Serializable] 2 public class Computer:ICloneable 3 { 4 public Computer(string brand) 5 { 6 Brand = brand; 7 } 8 public Computer() 9 { } 10 public string Brand { get; set; } 11 12 public object Clone() 13 { 14 return this.MemberwiseClone(); 15 } 16 }
Person类
1 [Serializable] 2 public class Person 3 { 4 public string Name { get; set; } 5 public int Age { get; set; } 6 public Computer MyComputer { get; set; } 7 8 /// <summary> 9 /// 浅拷贝,调用MemberwiseClone方法 10 /// </summary> 11 /// <returns></returns> 12 public Person ShallowCopy() 13 { 14 return (Person)this.MemberwiseClone(); 15 } 16 17 /// <summary> 18 /// 深拷贝,通过序列化的方式 19 /// </summary> 20 /// <returns></returns> 21 public Person DeepCopy() 22 { 23 //创建序列化对象 24 BinaryFormatter binaryFormatter = new BinaryFormatter(); 25 using (MemoryStream memoryStream = new MemoryStream()) 26 { 27 //序列化对象到内存流中 28 binaryFormatter.Serialize(memoryStream, this); 29 //设置内存流中的位置 30 memoryStream.Position = 0; 31 //反序列化 32 return (Person)binaryFormatter.Deserialize(memoryStream); 33 } 34 } 35 }
在控制台程序中的代码
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Person p = new Person(); 6 p.Name = "张三"; 7 p.Age = 12; 8 p.MyComputer = new Computer("惠普笔记本"); 9 //浅拷贝 10 Person p1 = p.ShallowCopy(); 11 //深拷贝 12 Person p2 = p.DeepCopy(); 13 Computer c = p.MyComputer; 14 Computer c1 = p1.MyComputer; 15 Computer c2 = p2.MyComputer; 16 Console.ReadKey(); 17 } 18 }
以上代码中浅拷贝是通过MemberwiseClone方法实现的,深拷贝是通过序列化的方式实现的。
其实只用MemberwiseClone方法也可以实现深拷贝,代码如下
先声明一个Student类,不用序列化,可以不打标记
1 public class Student:ICloneable 2 { 3 public string Name { get; set; } 4 public int Age { get; set; } 5 public Computer MyComputer { get; set; } 6 7 /// <summary> 8 /// 实现接口ICloneable的Clone方法 9 /// </summary> 10 /// <returns></returns> 11 public object Clone() 12 { 13 //浅拷贝 14 return this.MemberwiseClone(); 15 } 16 /// <summary> 17 /// 浅拷贝 18 /// </summary> 19 /// <returns></returns> 20 public Student ShallowCopy() 21 { 22 return (Student)this.Clone(); 23 } 24 /// <summary> 25 /// 深拷贝 26 /// </summary> 27 /// <returns></returns> 28 public Student DeepCopy() 29 { 30 Student s = (Student)this.Clone(); 31 s.MyComputer = (Computer)this.MyComputer.Clone(); 32 return s; 33 } 34 }
控制台中的代码如下
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Student s = new Student(); 6 s.Name = "张三"; 7 s.Age = 12; 8 s.MyComputer = new Computer("惠普笔记本"); 9 //浅拷贝 10 Student s1 = s.ShallowCopy(); 11 //深拷贝 12 Student s2 = s.DeepCopy(); 13 14 Computer c = s.MyComputer; 15 Computer c1 = s1.MyComputer; 16 Computer c2 = s2.MyComputer; 17 Console.ReadKey(); 18 } 19 }
以上是个人理解,如有问题请指正
浙公网安备 33010602011771号