为什么不能为每个循环修改一个集合 [英] Why can't you modify a collection in a for each loop

查看:170
本文介绍了为什么不能为每个循环修改一个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你复制它,为什么能最好地解释为什么要替换使用foreach循环的集合元素?示例:

How can you best explain why replacing an element of a collection you are looping using foreach is permited if you make a copy of it. Example:

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


推荐答案

最佳答案是List对其列表项进行某种跟踪,并且可以按照您的要求更新其项目,但是简单的IEnumerable不会这样,因此它不允许您更改它们。

The Best answer would be that List has some kind of Tracking over its list items and can update its items as you ask but a simple IEnumerable does not so it will not allow you to change them.

这篇关于为什么不能为每个循环修改一个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆