日期:2014-05-17  浏览次数:20802 次

新建一个实体student,list<student> a添加数据后,清空数据用a.clear()与a=new list<student>哪一种,有啥区别
新建一个实体student,list<student> a添加数据后,清空数据用a.clear()与a=new list<student>哪一种,有啥区别

是不是a=new list<student>后的内存地址就跟原来a的地址不一样了?

------解决方案--------------------
对啊。
一个是清除原先列表对象的元素,还是那个对象,元素没了。
一个是新建一个没有元素的空列表对象。

如果同时有几个对象引用,那么差异就来了:
List<Student> a = new List<Student>() { new Student() { id = 1, name = "a"} };
List<Student> b = a;
a.Clear();
Console.WriteLine(b.Count());

List<Student> a = new List<Student>() { new Student() { id = 1, name = "a"} };
List<Student> b = a;
a = new List<Student>();
Console.WriteLine(b.Count());

------解决方案--------------------
直接 清空 就行了,不要 new一个,new一个 将重新开辟一个新的内存空间。