【发布时间】:2012-11-06 04:00:42
【问题描述】:
当我在 lstCopy 中创建原始列表 lstStudent 的副本并将 lstCopy 发送到修改函数时,lstStudent 也会被修改。我想保持这个列表不变。
List<Student> lstStudent = new List<Student>();
Student s = new Student();
s.Name = "Akash";
s.ID = "1";
lstStudent.Add(s);
List<Student> lstCopy = new List<Student>(lstStudent);
Logic.ModifyList(lstCopy);
// "Want to use lstStudent(original list) for rest part of the code"
public static void ModifyList(List<Student> lstIntegers) {
foreach (Student s in lstIntegers) {
if (s.ID.Equals("1")) {
s.ID = "4"; s.Name = "APS";
}
}
}
【问题讨论】:
-
向我们展示
Logic.ModifyList的作用。 -
可能重复 - stackoverflow.com/questions/222598/… 您需要深度复制您的对象。
-
您想“深度”复制列表。否则,两个列表中的引用都指向相同的学生对象。见stackoverflow.com/questions/4226747/deep-copy-of-listt
-
public static void ModifyList(List
lstIntegers) { foreach (student s in lstIntegers) { if (s.ID.Equals("1")) { s.ID = "4"; s.Name = "APS"; } } } -
@user1801934
Student是您的班级(可以访问源代码)还是您无法控制?