【问题标题】:How to clone generic List<T> without being a reference?如何克隆通用 List<T> 而不是参考?
【发布时间】:2017-01-09 00:26:39
【问题描述】:

我有一个 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。 我该怎么做?

【问题讨论】:

    标签: c# generics clone


    【解决方案1】:

    您需要进行深度克隆。也就是克隆 Student 对象。否则,您有两个单独的列表,但都指向同一个学生。

    您可以在 CopyList 方法中使用 Linq

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

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

    这看起来像:

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

    在您的学生班级内。

    那么你可以简单地写

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

    在您的 CopyList 方法中。

    【讨论】:

    • 这样吗? var newList = oldList.Select(o =&gt; new Student { id = o.id, name = o.name }).toList(); 但出现错误。
    • 我现在用一种实际上更好的方法编辑了我的答案,因为它适用于封装。在实际复制/克隆它的 Student 类中创建一个公共方法 Copy。然后只需在选择中使用该方法。这样它就可以克隆私有和受保护的字段。
    • 约翰:好的,它运行良好。非常感谢!
    猜你喜欢
    • 2014-07-03
    • 2012-07-27
    • 2017-05-19
    • 2014-11-25
    • 2013-02-07
    • 2016-05-18
    • 2020-11-19
    相关资源
    最近更新 更多