怎样list A里面的所有对象赋值给另一个list B,为啥小弟我有时可以直接用等号赋值,有时又必须要foreach循环赋值
怎样list<student> A里面的所有对象赋值给另一个list<student> B,为啥我有时可以直接用等号赋值,有时又必须要foreach循环赋值
怎样list<student> A里面的所有对象赋值给另一个list<student> B,为啥我有时可以直接用等号赋值,有时又必须要foreach循环赋值才能真正取到A中的所有对象?
是不是下面两种方法都可以?(有时觉得只能用第二种)
1.list<student> B=A; (应该和list<student> B=new list<student>();B=A;一样的?)
2.foreach(var item in B)
B.ADD(item);
------解决方案--------------------
第一种写法,A 和B指向相同的引用,当A改变时,B也会跟着改变
第二种守法,A的心迹不会影响到B
给你写了个DEMO,希望你能理解:
怎样list<student> A里面的所有对象赋值给另一个list<student> B,为啥我有时可以直接用等号赋值,有时又必须要foreach循环赋值才能真正取到A中的所有对象?
是不是下面两种方法都可以?(有时觉得只能用第二种)
1.list<student> B=A; (应该和list<student> B=new list<student>();B=A;一样的?)
2.foreach(var item in B)
B.ADD(item);
------解决方案--------------------
第一种写法,A 和B指向相同的引用,当A改变时,B也会跟着改变
第二种守法,A的心迹不会影响到B
给你写了个DEMO,希望你能理解:
- C# code
void Main() { List<Student> A=new List<Student> { new Student{ Id=1, Name="Tim"}, new Student{ Id=2, Name="SCAUSCNU"} }; List<Student> B=A; List<Student> C=new List<Student>(); A.ForEach(a=>C.Add(a)); Console.WriteLine(A.Count()); //2 Console.WriteLine(B.Count()); //2 Console.WriteLine(C.Count()); //2 A.Add(new Student{ Id=3, Name="****"}); Console.WriteLine(); Console.WriteLine(A.Count()); //3 Console.WriteLine(B.Count()); //3 注意此处为何是3 ??? Console.WriteLine(C.Count()); //2 } public class Student { public int Id{get;set;} public string Name{get;set;} }
------解决方案--------------------
1楼居然是黄色网站,嘎嘎
用第二种方法
第一种方法是直接把该a赋值给 b,把a的引用地址给了b,这个时候,如果a改变了,b也会跟着改变,因为b的地址就是a.
list<student> B=new list<student>();B=A; 和list<student> B=A 是一样的,都是把a的引用地址给了a,楼主可以看看值类型和引用类型相关的知识
第二种方法是把a集合中的值给了b,a的改变,和b没有关系了