C# - 从包含原始副本的数组中删除一个对象
我在以下结构中持有一个阵列 列表[] Pagestore =新列表[2]; 数组的每个单元格将包含页面对象列表。
我编写了一个在循环中运行的函数,并且在每次迭代中都创建了一个新的页面列表。 我将列表保留在上面的列表中。 在每次迭代之前,我删除页面的内容,并在数组本身上完成删除。
如何防止这一点,以使阵列保存我保存的记录?
我的代码:
List<Page>[] pageStore = new List<Page>[2];
public void LoadExcel(Dictionary<string,string[]> FilePaths){
List<Page> pages = new List<Page>();
int pageStoreIndex = 0;
foreach (KeyValuePair<string, string[]> entry in
FilePaths) {
pages.Clear();
for (int i = 0; i < entry.Value.Length; i++) {
if (i == 0)
pages = fileManager.ParseExcelToObjects(excelDataSet,
ProjectTypeSelected.Name,entry.Key.Equals(Enum.Enums.ConnectorSide.COMBINED.ToString()) ? false : true);
...
...
}
if (pages.Count > 0)
pageStore[pageStoreIndex++] = pages;
}
}
page.clear()也清除了Pagestore。
I hold an array in the following structure
List[] pageStore = new List[2];
Each cell of the array will contain a list of Page objects.
I wrote a function that ran in a loop and in each iteration creates a new list of Page.
I keep the list created in the above List.
Before each iteration I delete the contents of pages and the deletion is also done on the array itself.
How can this be prevented so that the array will keep the records I saved?
my code :
List<Page>[] pageStore = new List<Page>[2];
public void LoadExcel(Dictionary<string,string[]> FilePaths){
List<Page> pages = new List<Page>();
int pageStoreIndex = 0;
foreach (KeyValuePair<string, string[]> entry in
FilePaths) {
pages.Clear();
for (int i = 0; i < entry.Value.Length; i++) {
if (i == 0)
pages = fileManager.ParseExcelToObjects(excelDataSet,
ProjectTypeSelected.Name,entry.Key.Equals(Enum.Enums.ConnectorSide.COMBINED.ToString()) ? false : true);
...
...
}
if (pages.Count > 0)
pageStore[pageStoreIndex++] = pages;
}
}
page.Clear() cleared pageStore also.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要创建列表的副本。
You need to create a copy of the list.
像大多数.NET对象一样,
list&lt; t&gt;
是一种参考类型。您的行:只是存储对单页实例的引用。它不会复制跨越值。每个数组条目都指向同一列表。
正如其他答案所说,如果要保留单独的列表,则需要每次创建一个新列表:
Like most .Net objects,
List<T>
is a reference type. Your line:is just storing a reference to the single pages instance. It's not copying the values across. Every array entry is pointing at the same list.
As other answers have said, you need to create a new list each time if you want to keep separate lists:
您已将Pagestore中的值分配为页面对象。您需要使用
list&lt; t&gt;
的复制构造函数创建一个新对象:You've assigned the value in pageStore to be the pages object. You'll need to create a new object using
List<T>
's copy constructor: