如何使用$之前List.Clear已经创建p $ pserve列表() [英] How to preserve lists already created before using List.Clear()
问题描述
当我将数据添加到一个列表
,那么该列表追加到另一个列表中,然后用 List.Clear()
原来的名单上,它倒空一切,已经追加的列表不preserved。
When I add data to a List
, then append that list to another list, then use List.Clear()
on the original list, it empties everything and the lists already appended aren't preserved.
下面就是我讲的一个例子。可以说,我做2列出如下:
Here's an example of what I'm talking about. Lets say I make 2 lists like this:
List<int> list = new List<int>();
List<List<int>> list2 = new List<List<int>>();
for(int i=0;i<10;i++){
for(int i2=0;i2<10;i2++){
list.Add(i2);
}
list2.Add(list);
list.Clear();
}
当我运行 list.Clear()
它清除掉所有我已经追加到pre-现有列表的列表2
When I run list.Clear()
it clears out all of the pre-existing lists I already appended to list2
我知道一个变通将重新安排code是这样的:
I know a work-around would be to re-arrange the code like this:
List<List<int>> list2 = new List<List<int>>();
for(int i=0;i<10;i++){
List<int> list = new List<int>(); //<- moved inside the for
for(int i2=0;i2<10;i2++){
list.Add(i2);
}
list2.Add(list);
}
不过,这是正常的行为呢?是否有可能preserve的pre-附加列表?
But is this normal behavior? Is it possible to preserve the pre-appended lists?
推荐答案
类作为参考,并且列表与LT通过; T&GT;
是一类。因此,当你明确的名单还会清除在list2中引用传递的数据。请参见列表 - 做我传递对象或引用的更多细节?
Classes are passed by reference and List<T>
is a class. Accordingly, when you clear list it also clears the data passed by reference in list2. See List - do I pass objects or references? for more details.
这应该解决您的例子所示的问题,并创建列表
之前添加到列表2
的新副本结算列表
:
This should solve the issue shown in your example and create a new copy of list
to add to list2
before clearing list
:
List<int> list = new List<int>();
List<List<int>> list2 = new List<List<int>>();
for(int i=0;i<10;i++){
for(int i2=0;i2<10;i2++){
list.Add(i2);
}
list2.Add(list.ToList()); //modified to create a new List when adding
list.Clear();
}
又见乔恩斯基特的参数传递的C#一些更广泛的了解如何参数传递在C#中,特别是与引用类型。
See also Jon Skeet's Parameter passing in C# for some broader information on how parameters are passed in C#, especially relating to reference types.
这篇关于如何使用$之前List.Clear已经创建p $ pserve列表()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!