以下内容借鉴了 以下大神的作品:
http://zhangzhanlei1988.iteye.com/blog/2024883
http://www.manew.com/thread-39776-1-1.html
ArrayList List 等迭代集合执行移除(remove) 操作容易犯错 解决这个问题有两种方式:
1,迭代器 IEnumerator 代码如下:
private List<int> _testList = new List<int>(new int[] {1,2,3,4,5});
void testList()
{
// foreach(var item in _testList)
// {
// Debug.Log(item*item);
// }
IEnumerator<int> itList = GetEnumeratorTest();
while(itList.MoveNext())
{
Debug.Log("GetEnumeratorTest a " + _testList.Count);
if(3 == (int)itList.Current)
{
Debug.Log(itList.Current);
_testList.Remove((int)itList.Current);
Debug.Log("GetEnumeratorTest c " + _testList.Count);
_testList.Add(6);
Debug.Log("GetEnumeratorTest d " + _testList.Count);
}
Debug.Log("GetEnumeratorTest b" + _testList.Count);
}
Debug.Log("_testList.GetEnumerator();");
IEnumerator it = _testList.GetEnumerator();
while(it.MoveNext())
{
Debug.Log(it.Current);
Debug.Log("_testList " + _testList.Count);
}
}
public IEnumerator<int> GetEnumeratorTest()
{
//此处应该for 不能使用foreach
for(int item = 0 ;item < _testList.Count;item++)
{
yield return _testList[item];
}
}
2,for循环 这种方式不用代码大家也都知道
面试的时候很多公司都会问这个问题
例如下面的问题
下列代码在运行中会发生什么问题? 如何避免?
List Testlist = new List(new int[]{ 1,2,3,4,5 });
foreach (var item in TestList)
Console.Writeline(item * item);
TestList.Remove(item);