gpt4 book ai didi

c# - 如何在没有引用的情况下克隆通用 List

转载 作者:太空宇宙 更新时间:2023-11-03 23:10:50 24 4
gpt4 key购买 nike

我有一个通用的 C# 对象列表,并希望克隆该列表。

List<Student> listStudent1 = new List<Student>();
List<Student> listStudent2 = new List<Student>();

我在下面使用了扩展方法,但它不能:(当 listStudent2 发生变化时 -> 影响 listStudent1)

public static List<T> CopyList<T>(this List<T> oldList)
{
var newList = new List<T>(oldList.Capacity);
newList.AddRange(oldList);

return newList;
}

我想继续在 listStudent2 中添加元素或进行更改而不影响 listStudent1。我该怎么做?

最佳答案

您需要进行深度克隆。那就是克隆 Student 对象。否则你有两个单独的列表,但它们仍然指向相同的学生。

您可以在 CopyList 方法中使用 Linq

var newList = oldList.Select(o => 
new Student{
id = o.id // Example
// Copy all relevant instance variables here
}).toList()

您可能想要做的是让您的 Student 类能够创建一个自身的克隆,这样您就可以简单地在 select 中使用它,而不是在那里创建一个新的学生。

这看起来像:

public Student Copy() {
return new Student {id = this.id, name = this.name};
}

在您的学生类(class)中。

那么你只需写

var newList = oldList.Select(o => 
o.Copy()).toList();

在您的 CopyList 方法中。

关于c# - 如何在没有引用的情况下克隆通用 List<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39266116/

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