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

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

    We know about this issue, it was an oversight when it was originally written. Unfortunately, we can't change it because it would now prevent this previously working code from running:

            var list = new List();
            list.Add("Foo");
            list.Add("Bar");
    
            list.ForEach((item) => 
            { 
                if(item=="Foo") 
                    list.Remove(item); 
            });
    

    The usefulness of this method itself is questionable as Eric Lippert pointed out, so we didn't include it for .NET for Metro style apps (ie Windows 8 apps).

    David Kean (BCL Team)

提交回复
热议问题