c# - 如何在修改其副本时保持通用列表不变?

标签 c# list

当我在 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"; 
        } 
    } 
}

最佳答案

您也可以通过使用二进制格式化程序在没有可克隆接口(interface)的情况下实现此目的: 注意:作为对象图一部分的所有类都必须标记为可序列化。

void Main()
{
   var student1=new Student{Name="Bob"};
   var student2=new Student{Name="Jim"};

   var lstStudent=new List<Student>();
   lstStudent.Add(student1);
   lstStudent.Add(student2);

   var lstCopy=new List<Student>(lstStudent);
   var clone=Clone(lstStudent);

   student1.Name="JOE";

   lstCopy.Dump();
   lstStudent.Dump();
   clone.Dump();

}

public List<Student> Clone(List<Student> source)
{

   BinaryFormatter bf=new BinaryFormatter();
   using(var ms=new MemoryStream())
   {
     bf.Serialize(ms,source);
     ms.Seek(0,0);
     return (List<Student>)bf.Deserialize(ms);
   }
}

[Serializable]
public class Student
{
  public string Name { get; set; }
}

输出:

5List<Student> (2 items) 4  
Name 
JOE 
Jim 

5List<Student> (2 items) 4  
Name 
JOE 
Jim 

5List<Student> (2 items) 4  
Name 
Bob 
Jim 

代码被格式化为转储到 LINQPad

编辑: 在无法实现 ICloneable 的情况下,这是一个选项。适用时,对接口(interface)进行编码。换句话说,您可以在学生对象上实现ICloneable,并在Clone() 方法中使用BinaryFormatter 逻辑;但是,作为开发人员,您可以选择自己决定要做什么。选项不一定是建议,建议也不总是一个选项。有时您必须采取必要的行动来完成一项任务,这就是选项发挥作用的时候。

这是一种被广泛接受的深度克隆方法: How do you do a deep copy of an object in .NET (C# specifically)?

关于c# - 如何在修改其副本时保持通用列表不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13244161/

相关文章:

c# - 如何从序列中间切掉一些元素?

c# - 如何使用 makecert 创建证书颁发机构证书?

Java链接列表无法将项目添加到末尾

c++ - C++ 中的双向链表、链表和动态数组

c# - 在c#中使用字符串数据类型列表创建元组

c# - 不可能两次运行 IAsyncEnumerable 的枚举?

c# - 忽略 Web 服务中的证书错误?

C# 不捕获方法返回值仍然需要对返回类型的引用

java - 在 Java 中克隆迭代器

Python 函数到 'rotate' 网格 90 度与 for 循环