内容简介:翻译自:https://stackoverflow.com/questions/1114735/when-items-change-while-being-enumerated-does-it-affects-the-enumeration
想象一下,在一个
foreach(var item in enumerable)
可枚举的项目发生了变化.它会影响当前的foreach吗?
例:
var enumerable = new List<int>();
enumerable.Add(1);
Parallel.ForEach<int>(enumerable, item =>
{
enumerable.Add(item + 1);
});
它将永远循环?
通常,它应该抛出异常.
列表<T> GetEnumerator()的实现提供一个Enumerator<T> MoveNext()方法看起来像这样的对象(来自Reflector):
public bool MoveNext()
{
List<T> list = this.list;
if ((this.version == list._version) && (this.index < list._size))
{
this.current = list._items[this.index];
this.index++;
return true;
}
return this.MoveNextRare();
}
private bool MoveNextRare()
{
if (this.version != this.list._version)
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
this.index = this.list._size + 1;
this.current = default(T);
return false;
}
在修改List的每个操作上修改(递增)list._version.
翻译自:https://stackoverflow.com/questions/1114735/when-items-change-while-being-enumerated-does-it-affects-the-enumeration
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Sovereign Individual
James Dale Davidson、William Rees-Mogg / Free Press / 1999-08-26 / USD 16.00
Two renowned investment advisors and authors of the bestseller The Great Reckoning bring to light both currents of disaster and the potential for prosperity and renewal in the face of radical changes ......一起来看看 《The Sovereign Individual》 这本书的介绍吧!
XML、JSON 在线转换
在线XML、JSON转换工具
HEX CMYK 转换工具
HEX CMYK 互转工具