如何创建 List<T> 的新深层副本(克隆)? [英] How create a new deep copy (clone) of a List<T>?
问题描述
在下面的一段代码中,
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace clone_test_01
{
public partial class MainForm : Form
{
public class Book
{
public string title = "";
public Book(string title)
{
this.title = title;
}
}
public MainForm()
{
InitializeComponent();
List<Book> books_1 = new List<Book>();
books_1.Add( new Book("One") );
books_1.Add( new Book("Two") );
books_1.Add( new Book("Three") );
books_1.Add( new Book("Four") );
List<Book> books_2 = new List<Book>(books_1);
books_2[0].title = "Five";
books_2[1].title = "Six";
textBox1.Text = books_1[0].title;
textBox2.Text = books_1[1].title;
}
}
}
我使用一个 Book
对象类型来创建一个 List
并用一些项目填充它,给它们一个唯一的标题(从 'one' 到 '五').
I use a Book
object type to create a List<T>
and I populate it with a few items giving them a unique title (from 'one' to 'five').
然后我创建List
.
从这一点来看,我知道它是列表对象的克隆,但是 book_2
中的 book 对象仍然是 books_1
中 book 对象的引用.通过对 books_2
的前两个元素进行更改,然后在 TextBox
中检查 book_1
的那些相同元素,可以证明这一点.
From this point, I know it's a clone of the list object, BUT the book objects from book_2
are still a reference from the book objects in books_1
. It's proven by making changes on the two first elements of books_2
, and then checking those same elements of book_1
in a TextBox
.
books_1[0].title 和 books_2[1].title
确实已更改为 books_2[0].title 和 books_2[1].title的新值代码>.
现在是问题
我们如何创建 List
的新硬拷贝?这个想法是 books_1
和 books_2
变得完全相互独立.
How do we create a new hard copy of a List<T>
? The idea is that books_1
and books_2
become completely independent of each other.
我很失望微软没有像 Ruby 那样使用 clone()
方法提供简洁、快速和简单的解决方案.
I'm disappointed Microsoft didn't offer a neat, fast and easy solution like Ruby are doing with the clone()
method.
帮助者真正棒的是使用我的代码并使用可行的解决方案对其进行更改,以便它可以被编译和工作.我认为这将真正帮助尝试了解针对此问题提供的解决方案的新手.
What would be really awesome from helpers is to use my code and alter it with a workable solution so it can be compiled and work. I think it will truly help newbies trying to understand offered solutions for this issue.
请注意,Book
类可能更复杂并具有更多属性.我尽量保持简单.
Note that the Book
class could be more complex and have more properties. I tried to keep things simple.
推荐答案
您需要创建新的 Book
对象,然后将它们放入新的 List
:
You need to create new Book
objects then put those in a new List
:
List<Book> books_2 = books_1.Select(book => new Book(book.title)).ToList();
更新:稍微简单一点... List
有一个方法叫做 ConvertAll
返回一个新列表:
Update: Slightly simpler... List<T>
has a method called ConvertAll
that returns a new list:
List<Book> books_2 = books_1.ConvertAll(book => new Book(book.title));
这篇关于如何创建 List<T> 的新深层副本(克隆)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!