foreach如何知道迭代的集合已被修改? [英] How can foreach know the iterated collection was modified?
问题描述
当我修改集合时,我用foreach
进行了遍历,但出现了异常.所以我很好奇foreach
(或运行时)如何检测到它.可以使用通用对象来做到这一点吗?
When I modified the collection I was iterating through with foreach
, I got an exception. So I'm just curious about how foreach
(or the runtime) detect that. Is it possible to do so with a general object?
推荐答案
集合本身必须对其进行检测.在标准库集合中,这是通过具有一个内部版本号来实现的,该版本号由每个操作进行修改,并在每次迭代时由迭代器进行检查(即,每次调用MoveNext
时,它都会检查版本号是否与该版本号相同).是创建迭代器的时间.
The collection itself has to detect it. In the standard library collections, this is achieved by having an internal version number which is modified by each operation, and checked by the iterator on each iteration (i.e. each time you call MoveNext
it checks that the version number is the same as it was when the iterator was created).
这篇关于foreach如何知道迭代的集合已被修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!