C# 对象的深复制和浅复制
2019年第一篇博客,好吧,又大了一岁了,继续加油吧。
正文:
C# 中的对象,众所周知是引用类型,那么如何复制对象Object呢,我们来看看下面这段代码:
public class User { public int UserId { get; set; } public string UserName { get; set; } public string PassWord { get; set; } public DateTime AddTime { get; set; } public User(int UserId, string UserName, string PassWord, DateTime AddTime) { this.UserId = UserId; this.UserName = UserName; this.PassWord = PassWord; this.AddTime = AddTime; } } public class People { public string abc { get; set; } public User User { get; set; } public People ShallowCopy() { return (People) this.MemberwiseClone(); } public People DeepCopy() { People other = (People)this.MemberwiseClone(); other.User = new User(User.UserId, User.UserName, User.PassWord, User.AddTime); other.abc = String.Copy(abc); return other; } }
People people = new People { abc = "1", User = new User(1,"1","1",DateTime.Now) }; People people4 = people; people.abc = "23"; people.User.PassWord = "2";
我们可以看到 将对象people 赋给了people4,那么我们修改people的值 people4 的值会如何呢?我们打断点试试,
我们可以看到people 和people4的值是一样的,什么原理呢,原来people4只是people的引用,people4指向people的地址,所以people的值改变,实际上people4引用的值就是people的地址,所以他们的值是一样的。
那么都是一样的话,我们需要怎么才能复制对象,而不是引用呢,
可以看到上面的代码中people类中定义了两个方法 ShallowCopy() 和 DeepCopy(),那这两个方法有什么作用呢,首先我们来看下面这段代码:
People people = new People { abc = "1", User = new User(1,"1","1",DateTime.Now) }; People people2 = people.ShallowCopy(); //浅拷贝方法 People people3 = people.DeepCopy(); //深拷贝方法 people.abc = "23"; people.User.PassWord = "2";
那这里 people2 和people3 的值是什么呢,打断点看看:
我们可以看到的是,people的值改变之后,people2中abc的值并没有改变,但是people2中User 中的password的值已经改变了,这就是对象的浅拷贝,是因为浅拷贝对象people2中的object类型指向的地址还是people的地址。
而people3 是深拷贝,深复制了一个新的对象,地址和原对象people不同,所以people的值改变,people3的值不会变。
这就是深拷贝和浅拷贝的区别。That's all, thank you
如有错误,欢迎指正,互相学习。谢谢!