由网友(陌上。少年。)分享简介:想象一下,在一个foreach(var item in enumerable)在枚举的事项发生变化的。它会影响当前的foreach?The enumerable items change. It will affect the current foreach?例如:var enumerable = new Li...
想象一下,在一个
foreach(var item in enumerable)
在枚举的事项发生变化的。它会影响当前的foreach?
The enumerable items change. It will affect the current foreach?
例如:
var enumerable = new List<int>();
enumerable.Add(1);
Parallel.ForEach<int>(enumerable, item =>
{
enumerable.Add(item + 1);
});
它会永远循环下去?
It will loop forever?
推荐答案
一般情况下,它应该抛出一个异常。
该名单,其中,T&GT;
实施的GetEnumerator()提供了一个枚举&LT; T&GT;
对象,其的MoveNext()
方法如下(从反射镜):
Generally, it should throw an exception.
The List<T>
implementation of GetEnumerator() Provides an Enumerator<T>
object whose MoveNext()
method looks like this (from 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._version
修改(递增)对每一个修改List操作。
The list._version
is modified (incremented) on each operation which modifies the List.
相关推荐
最新文章