C#:使用 foreach 或 for 循环从 ArrayList 中删除项目? [英] C#: remove items from an ArrayList with foreach or for loop?

查看:88
本文介绍了C#:使用 foreach 或 for 循环从 ArrayList 中删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 C# 编程和编程都很菜鸟(我之前学过一些基本的 Java).我正在尝试在 Unity3D 中使用 C#,我有一个问题:

I am quite a noob both with programming and programming with C# (I have learned some basic Java before). I am trying to play around with C# in Unity3D, and I have a question:

使用 for 循环而不是 foreach 迭代来删除 ArrayList 中的任何项目是否更好?

两者似乎都对我有用.Foreach 产生的编码略少,但 讨论在 Internet 似乎更喜欢 for 循环.哪个更好,为什么?

Both seems to work for me. Foreach produce slightly less coding but the discussions on the Internet seems to be favoring for-loop. Which is better and why?

for 循环版本:

public void RemoveUnitFromList(GameObject Unit) {
    if (SelectedUnitList.Count > 0) {
        for (int i = 0; i < SelectedUnitList.Count; i++) {
            GameObject ArrayListUnit = SelectedUnitList[i] as GameObject;
            if (ArrayListUnit == Unit) {
                SelectedUnitList.RemoveAt(i);
                // some other codes
            }
        }
    }
}

foreach 版本:

foreach version:

public void RemoveUnitFromList(GameObject Unit) {
    if (SelectedUnitList.Count > 0) {
        foreach (GameObject ArrayListUnit in new ArrayList(SelectedUnitList)) {
            if (ArrayListUnit == Unit) {
                SelectedUnitList.Remove(ArrayListUnit);
                // some other codes
            }
        }
    }
}

上面的任何一个代码片段对我来说都很好.我只想研究两者的区别.但是,将 in new ArrayList(SelectedUnitList) 更改为 in SelectedUnitList 不起作用:

Either of the code snippets above works fine for me. I only want to study the difference between the two. However, changing in new ArrayList(SelectedUnitList) to in SelectedUnitList did not work:

public void RemoveUnitFromList(GameObject Unit) {
    if (SelectedUnitList.Count > 0) {
        foreach (GameObject ArrayListUnit in SelectedUnitList) {
            if (ArrayListUnit == Unit) {
                SelectedUnitList.Remove(ArrayListUnit);
                // some other codes
            }
        }
    }
}

上面的代码可能会产生以下错误:

The above code could produce the following error:

InvalidOperationException: List has changed.
System.Collections.ArrayList+SimpleEnumerator.MoveNext () (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections/ArrayList.cs:141)
Mouse3.RemoveUnitFromList (UnityEngine.GameObject Unit) (at Assets/Scripts/Mouse3.cs:216)
Mouse3.Update () (at Assets/Scripts/Mouse3.cs:85)

让我解释更多.该方法在游戏中动态运行.SelectedUnitList 是一个 ArrayList,用于在 RTS 游戏中收集选定的单位.该方法从 ArrayList 中删除取消选择的单位,因此 Unit 可以是 0、1 或更多.

Let me explains more. The method functions dynamically in game. The SelectedUnitList is an ArrayList used to collect selected unit in a RTS game. The method removes the deselected units from the ArrayList, so Unit could be 0, 1 or more.

Edit3(上次):感谢大家提供的所有信息.我认为评论中的@Seminda 回答了我的问题.

Edit3 (last time): Thank you all for all the information provided. I think @Seminda in the comments answered my question.

推荐答案

来自 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.

这篇关于C#:使用 foreach 或 for 循环从 ArrayList 中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆