C#关于Clone()方法的介绍
日常啪啪啪代码的时候,常常遇到浅复制与深复制的问题,下面就自己经验写写,有问题请留言!
例如我有一个简单的类:
class People { public int _age; public string _name; public People(int Age,string Name) { _age = Age; _name = Name; } }
常见的赋值语句,如:
People Mike = new People(12,"Mike"); People Mike2 = Mike;
这是浅复制,共享同一块内存,类似指针,即Mike2与Mike对象同时指向了Mike新建时所申请的内存。
现在我为People类增加一个Clone()方法:
class People { public int _age; public string _name; public People(int Age,string Name) { _age = Age; _name = Name; } public object Clone() { People MySelf = new People(this._age,this._name); return MySelf; } }
很明显,调用Clone()方法返回的对象是一个全新的对象,是新实例化出来的对象但是与原对象在值上相等。
People Mike = new People(12,"Mike"); People Mike2 = Mike; People Mike3 = Mike.Clone() as People;
Mike2与Mike3在值上相等,但实际是完全独立的对象。
Mike2._name = "Jone"; //执行上述代码后,Mike的_name属性跟着改变了,而Mike3不变。