c#学习笔记-深度复制 与浅度复制
程序员文章站
2022-07-01 16:18:59
关于值类型和引用类型: 浅度复制(shallow copy)只复制值类型(char,int )的值,而对于引用类型不会复制,浅度复制可以通过派生于System.Object的MemberwiseClone()方法来完成,这是一个受保护的方法。因为他并没有考虑引用类型成员,因此新对象的引用成员就会指向 ......
关于值类型和引用类型:
浅度复制(shallow copy)只复制值类型(char,int )的值,而对于引用类型不会复制,浅度复制可以通过派生于system.object的memberwiseclone()方法来完成,这是一个受保护的方法。因为他并没有考虑引用类型成员,因此新对象的引用成员就会指向源对象中的相同成员引用的对象
如果要创建成员的新实例(复制值,而不是复制引用)就需要用到深度复制(deep copy)
深度复制需要实现一个icloneable接口,如果使用这个接口需要实现它包含的clone()方法,这个方法返回一个system.object的值,
下面看下浅度复制:
1 public class company 2 { 3 public string value { get; set; } 4 } 5 6 public class phone 7 { 8 public string color { get; set; } 9 10 public company company = new company(); 11 12 public phone (string newcompany) 13 { 14 company.value = newcompany; 15 } 16 17 public object getcopy() 18 { 19 return memberwiseclone(); 20 } 21 }
1 static void main(string[] args) 2 { 3 phone phone = new phone("xiaomi"); 4 phone.color = "red"; 5 phone phone1 = (phone)phone.getcopy(); 6 console.writeline($"phone company:{phone.company.value} color: {phone.color}"); 7 console.writeline($"phone1 company:{phone1.company.value} color: {phone1.color}"); 8 9 console.writeline("浅度复制修改新对象的值"); 10 11 phone1.company.value = "huawei"; 12 phone1.color = "green"; 13 console.writeline($"phone company:{phone.company.value} color: {phone.color}"); 14 console.writeline($"phone1 company:{phone1.company.value} color: {phone1.color}"); 15 console.readkey(); 16 17 }
实验现象:
浅度复制在后引用类型修改后,原对象也跟着发生了改变
修改这个问题,可以使用深度复制
1 public class company 2 { 3 public string value { get; set; } 4 } 5 6 public class phone:icloneable 7 { 8 public string color { get; set; } 9 10 public company company = new company(); 11 12 public phone (string newcompany) 13 { 14 company.value = newcompany; 15 } 16 17 public object getcopy() 18 { 19 return memberwiseclone(); 20 } 21 22 public object clone() 23 { 24 phone newphone = new phone(company.value); 25 return newphone; 26 //newphone.company.value = this.company.value; 27 28 } 29 }
1 static void main(string[] args) 2 { 3 phone phone = new phone("xiaomi"); 4 phone.color = "red"; 5 phone phone1 = (phone)phone.clone(); 6 console.writeline($"phone company:{phone.company.value} color: {phone.color}"); 7 console.writeline($"phone1 company:{phone1.company.value} color: {phone1.color}"); 8 9 console.writeline("浅度复制修改新对象的值"); 10 11 phone1.company.value = "huawei"; 12 phone1.color = "green"; 13 console.writeline($"phone company:{phone.company.value} color: {phone.color}"); 14 console.writeline($"phone1 company:{phone1.company.value} color: {phone1.color}"); 15 console.readkey(); 16 17 }
实验现象