我有一个 C# 对象的通用列表,并且希望克隆该列表。
List<Student> listStudent1 = new List<Student>();
List<Student> listStudent2 = new List<Student>();
Run Code Online (Sandbox Code Playgroud)
我使用了下面的扩展方法,但它不能:(当 listStudent2 发生变化时 -> 影响 listStudent1)
public static List<T> CopyList<T>(this List<T> oldList)
{
var newList = new List<T>(oldList.Capacity);
newList.AddRange(oldList);
return newList;
}
Run Code Online (Sandbox Code Playgroud)
我想继续添加元素或在 listStudent2 中进行更改而不影响 listStudent1。我怎么做?
您需要进行深度克隆。即也克隆 Student 对象。否则,您有两个单独的列表,但它们仍然指向相同的学生。
您可以在 CopyList 方法中使用 Linq
var newList = oldList.Select(o =>
new Student{
id = o.id // Example
// Copy all relevant instance variables here
}).toList()
Run Code Online (Sandbox Code Playgroud)
您可能想要做的是让您的 Student 类能够创建自身的克隆,这样您就可以简单地在选择中使用它,而不是在那里创建一个新学生。
这看起来像:
public Student Copy() {
return new Student {id = this.id, name = this.name};
}
Run Code Online (Sandbox Code Playgroud)
在您的学生班级内。
然后你只需写
var newList = oldList.Select(o =>
o.Copy()).toList();
Run Code Online (Sandbox Code Playgroud)
在您的 CopyList 方法中。