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

前端 未结 4 1996
礼貌的吻别
礼貌的吻别 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:54

    Because the ForEach attached to the List class internally uses a for loop that is directly attached to its internal members -- which you can see by downloading the source code for the .NET framework.

    http://referencesource.microsoft.com/netframework.aspx

    Where as a foreach loop is first and foremost a compiler optimization but also must operate against the collection as an observer -- so if the collection is modified it throws an exception.

提交回复
热议问题