为什么我会收到InvalidOperation异常? [英] Why do I get InvalidOperation exception?

查看:97
本文介绍了为什么我会收到InvalidOperation异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

For i = 0 To ModifiableSetting.Count - 1
    Dim key = ModifiableSetting.Keys(i)
    ModifiableSetting(key) = True
Next



以上代码有效。下面的代码让我得到了例外。

他们应该导致相同的结果,为什么例外呢?


The above code works. The code below gets me the exception.
They should cause the same results so why the exception?

For Each key In ModifiableSetting.Keys
    ModifiableSetting(key) = False
Next







只是困惑



Leon

推荐答案

因为For Each循环正在改变循环的目标 - 这是禁止的!



for循环每次修改一个索引值,因此可以改变Keys集合的内容 - 甚至删除它们。这不会影响任何事情,因为每次循环都会重新计算对象数量的计数,因此即使添加或删除项目也不会影响当前位置。



但For Each不会完成该集合,它使用一个迭代器,每次循环时遍历集合。因此,当您尝试修改集合时,迭代器会检测到并抛出异常。
Because the For Each loop is altering the target of the loop - which is a no-no!

The for loop modifies an index value each time round, so it's fine to alter the content of the Keys collection - or even to delete them. That doesn't affect anything, because the Count of the number of objects is recalculated each time round the loop, so even adding or removing items doesn't affect the "current" location.

But a For Each doesn't "complete" the collection, it uses an iterator which which "travels" through the collection each time round the loop. As such, when you try to modify the collection the iterator detects that and throws an exception.


这篇关于为什么我会收到InvalidOperation异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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