开发者

Can I safely modify a VB collection's items while iterating over it (using For Each)?

开发者 https://www.devze.com 2023-04-04 09:06 出处:网络
Can I safely modify -I mean: remove and re-add on a different index position- any item that I iterate over using a For Each loop in VB? We are talking about the VB Microsoft.VisualBasic.Collection cla

Can I safely modify -I mean: remove and re-add on a different index position- any item that I iterate over using a For Each loop in VB? We are talking about the VB Microsoft.VisualBasic.Collection clas开发者_开发百科s.

And if yes: Is this by design, or an implementational detail, that I am building upon then?

I might be too lazy to search hard enough, but the dox don't seem to say anything about this.


The IEnumerator<T> spec says that you can't:

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.

Some collections might not follow this rule.


You can't modify a collection whilst iterating through it as you describe; i.e. you can't remove an item without getting an exception such as "collection was modified".

That's not to say you can't modify the items at all (do something other than add/remove).

If you run into this error, try refactoring your code e.g. using a for loop (often in reverse, to avoid offsetting the index counter).


No you can't. Rather make a copy of the collection to edit and use the copy afterwards.

0

精彩评论

暂无评论...
验证码 换一张
取 消