且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在“foreach"循环中修改列表的***方法是什么?

更新时间:2022-06-01 03:10:44

foreach 中使用的集合是不可变的.这在很大程度上是设计使然.

The collection used in foreach is immutable. This is very much by design.

正如 MSDN 上所说:

foreach 语句用于遍历集合以获得您想要的信息,但可以不可用于添加或删除项目从源头收集避免不可预测的副作用.如果你需要添加或删除项目源集合,使用 for 循环.

The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.

链接中的帖子提供by Poko 表示这在新的并发集合中是允许的.

The post in the link provided by Poko indicates that this is allowed in the new concurrent collections.