如何克隆通用列表而不是作为参考
本文关键字:参考 何克隆 列表 | 更新日期: 2023-09-27 18:05:19
我有一个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中使用它,而不是在那里创建一个新的Student。
这看起来像:
public Student Copy() {
return new Student {id = this.id, name = this.name};
}
在你的学生班级。
那么你可以直接写
var newList = oldList.Select(o =>
o.Copy()).toList();