集合已修改;枚举操作可能不会执行 - 为什么?操作

由网友(大湿胸)分享简介:我列举了实现IList的集合,而枚举过程中,我改变这个集合。我得到的错误,集合被修改;枚举操作可能不会执行I'm enumerating over a collection that implements IList, and during the enumeration I am modifying the col...

我列举了实现IList的集合,而枚举过程中,我改变这个集合。我得到的错误,集合被修改;枚举操作可能不会执行

I'm enumerating over a collection that implements IList, and during the enumeration I am modifying the collection. I get the error, "Collection was modified; enumeration operation may not execute."

我想知道为什么迭代过程中修改集合中的一个项目时会出现此错误。我已经将我的foreach循环一个for循环,但我想知道为什么这个错误发生在详细信息。

I want to know why this error occurs when modifying a item in the collection during iteration. I've already converted my foreach loop to a for loop, but I want to know the 'details' on why this error occurs.

推荐答案

在IEnumerable文档:

这是枚举仍然有效,只要集合保持不变。如果更改了收集,如添加,修改或删除元素,枚举数将失效且不可恢复,而且其行为是不确定的。

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.

我相信的理由这一决定是它不能保证所有类型的集合可以承受的修改,仍然preserve一个枚举状态。考虑一个链表 - 如果你删除一个节点,目前枚举是节点,该节点的参考可能是其唯一的国家。而一旦该节点被删除,下一个节点的提法将被设置为,有效无效的枚举状态,preventing进一步枚举。

I believe the reasoning for this decision is that it cannot be guaranteed that all types of collections can sustain modification and still preserve an enumerator state. Consider a linked list -- if you remove a node and an enumerator is currently on that node, the node reference may be its only state. And once that node is removed, the "next node" reference will be set to null, effectively invalidating the enumerator state and preventing further enumeration.

由于一些集合的实现将有很大的麻烦与这种情况下,就决定让这部分IEnumerable接口的合同。允许修改在某些情况下,而不是其他人是可怕混乱。此外,这将意味着现有的code可能依赖于修改集合枚举时会产生严重的问题,当集合实现改变。因此,使得在所有可枚举一致的行为是preferable。

Since some collection implementations would have serious trouble with this kind of situation, it was decided to make this part of the IEnumerable interface contract. Allowing modification in some situations and not others would be horribly confusing. In addition, this would mean that existing code that might rely on modifying a collection while enumerating it would have serious problems when the collection implementation is changed. So making the behavior consistent across all enumerables is preferable.

阅读全文

相关推荐

最新文章