如何在没有参考的情况下克隆通用列表<T>?

How to clone generic List<T> without being a reference?

我有一个通用的 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;
}

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

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

您可以在 CopyList 方法中使用 Linq

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

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

这看起来像:

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

在您的学生中 class。

那么你只需写

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

在您的 CopyList 方法中。