简体   繁体   English

foreach如何知道迭代集合被修改了?

[英]How can foreach know the iterated collection was modified?

When I modified the collection I was iterating through with foreach , I got an exception. 当我修改集合时,我正在使用foreach迭代,我得到了一个例外。 So I'm just curious about how foreach (or the runtime) detect that. 所以我只是好奇foreach (或运行时)如何检测到它。 Is it possible to do so with a general object? 是否可以使用一般对象?

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 (ie each time you call MoveNext it checks that the version number is the same as it was when the iterator was created). 在标准库集合中,这是通过具有由每个操作修改的内部版本号来实现的,并且在每次迭代时由迭代器检查(即,每次调用MoveNext它检查版本号是否与它时相同)迭代器已创建)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM