When I create a copy of the original list lstStudent in lstCopy and send the lstCopy to modification function, the lstStudent also gets modified. I want to keep this list unmodified.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"; } }} 解决方案 If your Student type is a class (reference type), a list will only contain references to those instances. This means that when you make a copy of your list, the copied list will also have only references that still point to the same Student instances. By copying your list you simply duplicated your references but not the instances. What you have after the copy is something like this:List 1 List 2 instance S1ref to S1 ref to S1 Name: Akashref to S2 ref to S2 ...... ...So if you do something like list1[0].Name = "Jim", you'll update the instance S1 and you'll see the change in both lists, since both lists refer to the same set of instances.What you need to do is create a clone of not only the list in this case but all the objects inside the list - you need to clone all your Student objects as well. This is called a deep copy. Something like this:class StudentList : List<Student>, ICloneable{ public object Clone () { StudentList oNewList = new StudentList (); for ( int i = 0; i < Count; i++ ) { oNewList.Add ( this[i].Clone () as Student ); } return ( oNewList ); }}You call this like so:StudentList oClonedList = lstStudent.Clone () as StudentList;You also need to make your Student class cloneable by implementing the ICloneable interface.Don't forget, though, that after this, you'll have 2 separate lists with 2 independent sets of Student objects - modifying one Studentinstance will have no effect on students in your other list. 这篇关于修改副本后,如何保持通用列表不变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 1403页,肝出来的..
09-06 20:48