Person类:
public class Person { public string Name { get; set; } public int Age { get; set; } public Address Address { get; set; } public Person Clone() { //MemberwiseClone方法实现浅拷贝 return this.MemberwiseClone() as Person; } }
Address类
public class Address { public string Province { get; set; } public string City { get; set; } }
具体调用(浅拷贝)
Person person = new Person() { Name = "zhangsan", Age = 23, Address = new Address() { City = "shanghai", Province = "china" } }; Person person1 = person.Clone(); Console.WriteLine(person.Equals(person1)); //false person1.Address.Province = "lisi"; Console.WriteLine(person.Address.Province); //lisi
通过object.MemberWiseClone()获取一个对象的实例属于浅拷贝,对实例的简单类型属性进行全值拷贝(包含string类型),对复杂类型属性只拷贝了引用,源对象的引用类型值改变了,则克隆出来的对象对应的属性值也会进行修改,因为操作的是同一个地址指针所指向的空间
深拷贝
Person person = new Person() { Name = "zhangsan", Age = 23, Address = new Address() { City = "shanghai", Province = "china" } }; string objstr = JsonConvert.SerializeObject(person1); Person person2 = JsonConvert.DeserializeObject<Person>(objstr);
深拷贝 序列化实现 ,相当于把源对象的值存放在了string字符串当中,当做中间变量,反序列化字符串得到的对象是完全开辟的新空间,它的引用类型字段的地址所指向的是不同的空间,所以修改克隆出来的实例的值并不会修改源对象的值
标签:set,string,Person,原型,Address,拷贝,设计模式,public From: https://www.cnblogs.com/liuzongxian/p/16866726.html