为什么不能修改 for each 循环中的集合
本文关键字:集合 循环 each 不能 修改 for 为什么 | 更新日期: 2023-09-27 18:33:31
你如何最好地解释为什么如果你复制它,就允许替换你正在使用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
因为Enumerator
中继集合中的count
元素,并且您不必在迭代期间更改它。
如果您创建列表的副本(回答您的问题(,则会遍历要更改的集合的副本。那是。
最好的答案是List对其列表项具有某种跟踪功能,并且可以根据您的要求更新其项目,但简单的IEnumerable则不然,因此它不允许您更改它们。
你的物品是什么类型? 修改方法有什么作用? 我无法重现您可以使用第二个选项做什么。 我无法编译这个:
int[] nn = new int[] { 1, 2 };
foreach (var n in nn.ToList())
n++;
错误:无法分配给"n",因为它是"foreach 迭代变量">