Does the foreach loop in C# guarantee an order of evaluation?

前端 未结 4 1929
时光取名叫无心
时光取名叫无心 2020-12-30 22:52

Logically, one would think that the foreach loop in C# would evaluate in the same order as an incrementing for loop. Experimentally, it does. However, there appears to be no

4条回答
  •  太阳男子
    2020-12-30 23:18

    For what it's worth, you can look up a lot of this in Reflector. In mscorlib, System.Array implements IEnumerable (as mentioned), and Array#GetEnumerator returns an ArrayEnumerator. Here's the body of ArrayEnumerator#MoveNext:

    public bool MoveNext()
    {
        if (this._complete)
        {
            this.index = this.endIndex;
            return false;
        }
        this.index++;
        this.IncArray();
        return !this._complete;
    }
    

    That's obviously one example, but the answer is: it's up to the implementer and you can find out most of the way they work experimentally, or by inspecting the source, in some cases.

提交回复
热议问题