T&GT;名单,LT深复印件; [英] Deep copy of List<T>
问题描述
我想做一个泛型列表的深层副本,并想知道是否有任何其他方式然后创建复制方法,一次竟在复制每个成员之一。我有一个类,它看起来有点像这样的:
I'm trying to make a deep copy of a generic list, and am wondering if there is any other way then creating the copying method and actually copying over each member one at a time. I have a class that looks somewhat like this:
public class Data
{
private string comment;
public string Comment
{
get { return comment; }
set { comment = value; }
}
private List<double> traceData;
public List<double> TraceData
{
get { return traceData; }
set { traceData = value; }
}
}
和我有上面的数据,即列表℃的列表;数据&GT;
。我试图做的是情节名单的子集的跟踪数据到一个图形,可能会进行一些缩放或扫上的数据。我显然不需要绘制列表中的一切,因为他们不适合在屏幕上。
And I have a list of the above data, i.e List<Data>
. What I'm trying to do is plot a trace data of the subset of List onto a graph, possibly with some scaling or sweeping on the data. I obviously don't need to plot everything in the list because they don't fit into the screen.
我最初试图获取列表的使用 List.GetRange()
法的子集,但似乎下列表&LT;双&GT;
正在复制浅,而不是深复制。当我得到的子集再次使用List.GetRange(),我得到previously修改的数据,其他地方没有检索到的原始数据。
I initially tried getting the subset of the list using the List.GetRange()
method, but it seems that the underneath List<double>
is being shallow copied instead of deep copied. When I get the subset again using List.GetRange(), I get previously modified data, not the raw data retrieved elsewhere.
谁能给我对如何处理这个方向?非常感谢。
Can anyone give me a direction on how to approach this? Thanks a lot.
推荐答案
在C#中解决这个惯用的方法是实施的 ICloneable
在数据
,并写了 ,做深拷贝克隆
办法(然后presumably可以一次克隆列表的一部分 Enumerable.CloneRange
方法)。没有任何内置的伎俩或框架的方法,使其比这更容易。
The idiomatic way to approach this in C# is to implement ICloneable
on your Data
, and write a Clone
method that does the deep copy (and then presumably a Enumerable.CloneRange
method that can clone part of your list at once.) There isn't any built-in trick or framework method to make it easier than that.
除非内存和性能是一个真正的问题,我建议你尽量重新设计它的不可变运行数据
的对象,不过,来代替。它会风要简单得多。
Unless memory and performance are a real concern, I suggest that you try hard to redesign it to operate on immutable Data
objects, though, instead. It'll wind up much simpler.
这篇关于T&GT;名单,LT深复印件;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!