當我在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'一樣。 –
可能的重複 - http://stackoverflow.com/questions/222598/how-do-i-clone-a-generic-list-in-c 您需要深入複製您的對象。 –
你想「深入」複製列表。否則,兩個列表中的引用都指向相同的學生對象。見http://stackoverflow.com/questions/4226747/deep-copy-of-listt – MaximR