Why does List.ForEach allow its list to be modified?

前端 未结 4 1964
礼貌的吻别
礼貌的吻别 2021-01-31 13:02

If I use:

var strings = new List { \"sample\" };
foreach (string s in strings)
{
  Console.WriteLine(s);
  strings.Add(s + \"!\");
}
4条回答
  •  心在旅途
    2021-01-31 13:46

    It's because the ForEach method doesn't use the enumerator, it loops through the items with a for loop:

    public void ForEach(Action action)
    {
        if (action == null)
        {
            ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
        }
        for (int i = 0; i < this._size; i++)
        {
            action(this._items[i]);
        }
    }
    

    (code obtained with JustDecompile)

    Since the enumerator is not used, it never checks if the list has changed, and the end condition of the for loop is never reached because _size is increased at every iteration.

提交回复
热议问题