且构网

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

C#:使用 foreach 或 for 循环从 ArrayList 中删除项目?

更新时间:2023-12-02 20:29:46

来自 foreach 循环:

foreach 语句用于遍历集合以获取您想要的信息,但不能用于从源集合中添加或删除项目以避免不可预知的副作用.如果需要在源集合中添加或删除项目,请使用 循环.

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.

参考你的代码,注意以下几点:

Reference to your code, note following thing:

查看有关 ArrayList 的详细信息.通常***使用 List强>.列表不仅可以避免装箱或拆箱,还可以使代码更清晰、不易出错.

See details about the ArrayList. It is usually better to use List. Lists not only avoid boxing or unboxing, but they also lead to clearer and less bug-prone code.

更新:

foreach(您问题中的第二个片段)之所以有效,是因为您初始化了新的 ArrayList.

foreach (2nd snippet in your question) works because you initialize new ArrayList.

foreach (GameObject ArrayListUnit in new ArrayList(SelectedUnitList))

您已经初始化了冗余的 ArrayList 并将其仅用于迭代.但是,当您在 foreach 循环中从 ArrayList 中删除时,它来自实际的 ArrayList,即 SelectedUnitList.

You have initialized redundant ArrayList and used it just for iteration. But when you remove from ArrayList within foreach loop it is from actual ArrayList i.e. SelectedUnitList.

结论:

使用 for loop 避免冗余和从 ArrayList 中删除.

Use for loop to avoid redundancy and removing from the ArrayList.