检察ArrayList中关于Clone要领的引见:
竖立 System.Collections.ArrayList 的浅表副本。
很猎奇,浅表副本的观点,上msdn查阅后,诠释的意义比较艰涩一点,浅表复制鸠合是指仅仅复制鸠合元素,不论元素是值范例照样援用范例,然则Clone并不会复制对象(援用指向的对象)。新Clone后的鸠合中,援用照样指向同一个对象(本来鸠合中援用指向的对象)。
A shallow copy of a collection copies only the elements of the collection, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new collection point to the same objects that the references in the original collection point to.
一句话归纳综合,Clone完成的所谓浅表副本,Clone出来的对象复制了值范例,复制了援用,而未复制援用对象。这个时刻,能够就要问了,未复制援用对象是什么意义?经由过程代码是最好申明题目的,请看下面的代码,
//职员对象模子 public class Person { public string name { get; set; } public ContactInfo description { get; set; } public Person(string name, ContactInfo description) { this.description = description; this.name = name; } } //联络信息对象 public class ContactInfo { public string address { get; set; } public string telephone { get; set; } public ContactInfo(string address, string telephone) { this.address = address; this.telephone = telephone; } //跟新电话联络信息 public void UpdateTelephone(string telephone) { this.telephone = telephone; } }
新建一个ArrayList对象,并离别添加为一个援用对象,一个值范例数据
//ArrayList对象 ArrayList arr1 = new ArrayList(); //Person对象竖立,xiaoming援用Person对象 Person xiaoming = new Person("xiaoming",new ContactInfo("shanghai","18011113333")); //arr1援用xiaoming,如许arr1[0]也援用了Person对象 arr1.Add(xiaoming); //arr1中添加值范例整形5元素 arr1.Add(5);
我们经由过程Clone接口,Clone出一个arr1的浅表副本:
ArrayList cloneArr1 = arr1.Clone() as ArrayList;
如图所示:
离别测试,克隆出来的实例cloneArr1都复制了什么,我们离别check下值范例和援用范例的复制状况。先看值范例的复制状况:
cloneArr1[1]=6;
我们搜检下初始的鸠合arr1[1]的元素转变了吗?
未转变,值照样5,这申明,Clone后,值范例也复制出来,而且放到内存栈中。
Check下援用范例有无从新从内存堆中从新拓荒空间,修正xiaoming的联络-电话:
(cloneArr1[0] as Person).description.UpdateTelephone("170444455555");
这个时刻,我们再Check,初始鸠合arr1中xiaoming的联络方式转变了吗?
答案:转变了,和最新的170444455555一致。
这申明了对援用范例,浅表副本复制,只是复制援用,而未从新再内存堆中拓荒内存空间。(假如您对内存堆,内存栈,观点不是很清晰,请参考我总结的:C#.NET:内存治理story-变量竖立与烧毁)。
至此,我们对Clone的功用有了一个全新的认识了!浅表副本,援用范例只复制援用,不复制对象。!
那末假如说,我想完成了深度复制呢,也就是我新复制出来的对象不是仅仅复制援用, 而是复制对象!比如说,你需要在一个模板的基础上修正出5个版本的竖立,每一个版本投递到差别的企业上,版本1投给公司A,版本2投给公司B,。。。假如说这5个版本的差别仅仅是“我希冀到场某某公司”,某某换成5个公司对应的称号。
以上就是.NET框架-Clone详请引见的细致内容,更多请关注ki4网别的相干文章!