c# – 枚举时项目发生变化时是否会影响枚举?

栏目: C# · 发布时间: 6年前

内容简介:翻译自: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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Deep Learning

Deep Learning

Ian Goodfellow、Yoshua Bengio、Aaron Courville / The MIT Press / 2016-11-11 / USD 72.00

"Written by three experts in the field, Deep Learning is the only comprehensive book on the subject." -- Elon Musk, co-chair of OpenAI; co-founder and CEO of Tesla and SpaceX Deep learning is a for......一起来看看 《Deep Learning》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试