我有一个通用的 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 方法中。
我是一名优秀的程序员,十分优秀!