2012-05-09 101 views
-4

你怎么能最好地解释为什么如果你复制它,使用foreach替换你正在循环的集合的元素是被允许的。例如:为什么你不能修改每个循环中的集合

foreach(Item item in Items) 
{ 
    item.modify //or remove or add 
} 
// will not work 

foreach(Item item in Items.ToList()) 
{ 
    item.modify //or remove. or add 
} 

//will work altough i dont get it because i am now iterating trough the temporary list 
//and changing its elements. 
//In my understanding its not like im iterating the list(.ToList) and modifying the source items 
//(Items). A graphic representation would be welcome, my interest is to understand the 
//matter logically 
+2

因为如果你**榜上无名的副本**然后除去项目*原始列表*(它*不*被重复!)不会影响副本。 – 2012-05-09 06:48:07

+0

您需要找到列表的内部以及项目如何连接在一起,以及迭代器如何从一个元素移动到另一个元素,以了解为什么会发生这种情况(副本旁边)。这些列表通过指针连接在一起。从列表中删除项目时,所有列表都会更改,并且下一个循环中的迭代器不能相同。 – Aristos

+0

如果它使用列表进行迭代,那么logicaly它将使用相同的列表从中删除。因为即时通讯使用列表对象进行此操作。 – Freeman

回答

-1

最佳答案是List对列表项有某种跟踪,并且可以根据你的要求更新它的项目,但是一个简单的IEnumerable不会,因此它不会允许你改变它们。

0

因为Enumerator继电器在集合中元素的count和你不premitted迭代过程中更改它。

如果您制作列表的副本(回答您的问题),您可以遍历要更改的集合的副本。那是。

+0

我知道,但如果你做一个ToList()这个时候你不在列表项目上做同样的操作,但它没有这样做的问题。为什么? – Freeman

+0

@Freeman:ToList()在列表中创建一个新的**副本**,即。 – Tigran

+0

它是否每次迭代都会创建一个新的副本列表? – Freeman

-1

你的物品是什么类型?修改方法做了什么?我无法复制你可以用第二种方法做什么。我不能编译如下:

int[] nn = new int[] { 1, 2 }; 
foreach (var n in nn.ToList()) 
    n++; 

错误:无法分配给“N”,因为它是一个“的foreach迭代变量”

+0

我的项目是EntityObject类型。所以在我使用IEnumerable 的集合上IEnumerable 。 – Freeman

相关问题