gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:34:53 26 4
gpt4 key购买 nike

当我在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com