关于值类型和引用类型:
浅度复制(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 }
实验现象