C#_深拷贝与浅拷贝
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Runtime.Serialization.Formatters.Binary; 6 using System.Text; 7 using System.Threading.Tasks; 8 9 namespace _004深拷贝浅靠背 10 { 11 class Program 12 { 13 static void Main(string[] args) 14 { 15 16 Student s1 = new Student() { Id="123",Name="Joe",Age=16}; 17 //Student s2 = s1; //没有发生拷贝 对象只有一个 只是将引用赋值给了 s2 18 19 20 21 //Student s2 = new Student(); 22 //s2.Age = s1.Age; 23 //s2.Id = s1.Id; 24 //s2.Name = s1.Name; 25 //以上才叫发生了拷贝 26 27 28 29 //拷贝 一般通过 序列化 来完成拷贝 30 Student s2=new Student(); 31 BinaryFormatter bf = new BinaryFormatter(); 32 //这里使用的是 内存流 33 byte[] bs = new byte[1000]; 34 //定义一个内存流 并且将对象序列化到内存中 35 using(MemoryStream ms =new MemoryStream(bs)) 36 { 37 //将对象s1 序列化到内存当中去了 38 bf.Serialize(ms, s1); 39 } 40 //然后再将这个流反序列化回来 41 using (MemoryStream ms = new MemoryStream(bs)) 42 { 43 s2 = bf.Deserialize(ms) as Student; 44 } 45 Console.WriteLine(s2.Name + " "+ s2.Id + " <s2> "+ s2.Age); 46 47 48 49 50 s1.Tea = new Teacher() { Name="Zhao"}; 51 52 Student s3 = new Student(); 53 s3.Id = s1.Id; 54 s3.Age = s1.Age; 55 s3.Name = s1.Name; 56 s3.Tea = s1.Tea;//浅拷贝 将引用类型的对象直接指向 s3.Tea 没有创建新对象 赋值的是 对象的引用 57 58 Student s4 = new Student(); 59 s4.Id = s1.Id; 60 s4.Name = s1.Name; 61 s4.Age = s1.Age; 62 63 s4.Tea = new Teacher(); //深拷贝 将引用类型 重新new了 创建新对象 将原对象的值赋值过去 64 s4.Tea.Name = s1.Tea.Name; 65 66 67 } 68 } 69 70 71 /// <summary> 72 /// 如果要做拷贝的话 尽量不要在类中定义自动属性 73 /// </summary> 74 /// 75 [Serializable] 76 class Student 77 { 78 private string _id; 79 80 public string Id 81 { 82 get { return _id; } 83 set { _id = value; } 84 } 85 86 private string _name; 87 88 public string Name 89 { 90 get { return _name; } 91 set { _name = value; } 92 } 93 94 private int _age; 95 96 public int Age 97 { 98 get { return _age; } 99 set { _age = value; } 100 } 101 102 //自定义类型 103 private Teacher _tea; 104 internal Teacher Tea 105 { 106 get { return _tea; } 107 set { _tea = value; } 108 } 109 110 } 111 112 [Serializable] 113 class Teacher 114 { 115 private string _name; 116 117 public string Name 118 { 119 get { return _name; } 120 set { _name = value; } 121 } 122 } 123 124 125 126 127 }
仰望梦想的姿势