简体   繁体   中英

Does changing a item field in a Collection while iterating invalidates the collection?

If do:

foreach(var a in col) {
     a.X = 1;
}

Will my iterator over the collection become invalid?

Thanks

No. You can access the members of the items in the collection. Your code is valid.

What you can't do is modifying the collection itself (by removing or adding items to it) while iterating.

It shouldn't cause a problem. Only if you try to modify the contents of col by doing col.Remove or col.Add would I imagine there would be a problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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