如何创建一个列表℃的新型深复制(克隆); T&GT ;? [英] How create a new deep copy (clone) of a List<T>?
问题描述
在下面的一段code的,
In the following piece of code,
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;
}
}
}
我用图书
对象类型来创建一个列表&LT; T&GT;
,我和几个项目来填充它给他们一个独特的标题(从一到十二五)。
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').
然后,我创建列表&LT;图书&GT; books_2 =新的List&LT;图书&GT;(books_1)
。
从这一点来说,我知道这是列表对象的克隆,而是来自 book_2
在 books_1
。它通过在 books_2
的两个第一要素进行更改,然后检查在 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伪
。
现在的问题
我们如何创建一个新的硬拷贝一个列表&LT; T&GT;
?这个想法是, 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整齐,快速和容易的解决方案是用克隆做()
方法。
I'm disappointed Microsoft didn't offer a neat, fast and easy solution like Ruby are doing with the clone()
method.
将是真正真棒从助手是用我的code和一个可行的解决方案,改变它,所以它可以编译和工作是什么。我认为这将真正帮助新手试图理解这个问题提供的解决方案。
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.
编辑:请注意,图书
类可能会更加复杂,并有更多的特性。我试图让事情变得简单。
Note that the Book
class could be more complex and have more properties. I tried to keep things simple.
推荐答案
您需要创建新的图书
对象,然后把那些在一个新的列表
:
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();
更新:稍微简单... 列表&LT; T&GT;
有一个名为方法的 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));
这篇关于如何创建一个列表℃的新型深复制(克隆); T&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!