나는 프로그래밍과 프로그래밍에있어 C#으로 멍청하다. (나는 기본적인 자바를 배웠다.) 나는 Unity3D에서 C#을 함께 놀러하려고, 나는 질문이있다 : 그것은 ArrayList에있는 모든 항목을 제거하는 루프 대신 foreach는 반복 사용하는 것이 더C# : foreach 또는 for 루프를 사용하여 ArrayList에서 항목을 제거 하시겠습니까?
인가를?
모두 나를 위해 작동하는 것 같습니다. Foreach는 코딩을 약간 덜 생성하지만 discussions onthe Internet은 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 버전 :
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
에 변경 그러나 는 작동하지 않았다 :
public void RemoveUnitFromList(GameObject Unit) {
if (SelectedUnitList.Count > 0) {
foreach (GameObject ArrayListUnit in SelectedUnitList) {
if (ArrayListUnit == Unit) {
SelectedUnitList.Remove(ArrayListUnit);
// some other codes
}
}
}
}
Edit2가를 : 은 위의 코드는 다음과 같은 오류를 생산할 수 :
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
은 RTS 게임에서 선택된 유닛을 수집하는 데 사용되는 ArrayList입니다. 이 메서드는 ArrayList에서 선택 취소 된 유닛을 제거하므로 Unit
은 0, 1 이상일 수 있습니다.
편집 3 (마지막) : 제공된 모든 정보를 제공해 주셔서 감사합니다. 나는 코멘트에서 @Seminda가 나의 질문에 대답했다고 생각한다. foreach Loop에 MSDN 문서에서
힌트 : :이 경우
은 당신의 코드는 아래로 비등 그것은'new' 키워드에 관한 것입니다. Btw, if 문은 두 경우 모두 쓸모가 없습니다. – Mephy
실제로 코드는 [온라인 튜토리얼] (https://www.youtube.com/watch?v=vSshzqMpv20&index=9&list=PLcGWkWha2wFd5Azr14ZJjvfnAmUKM_3E7)에서 복사/수정되었으며 'Unit' 아무것도 가지고 있지 않습니까? 음 ... 힌트를 주셔서 감사합니다. 'new'키워드가 없으면 'foreach'가 작동하지 않습니다. 나는 내가 이해하지 않는 것을 생각한다. 스레딩과 관련이 있습니까? –
이 설명을 확인하고 코드에 적용하여 어떤 코드가 좋은지 확인하십시오. http://www.john.edu/pub/detnetperls.com/for-foreach – Seminda