C#:List .ForEach(…)对普通foreach循环的任何好处?
我想知道为什么List.ForEach(Action)
存在。
这样做有什么好处/差别:
elements.ForEach(delegate(Element element){ element.DoSomething(); });
过度
foreach(Element element in elements) { element.DoSomething();}
?
一个关键的区别是.ForEach方法可以修改底层集合。 使用foreach语法,如果这样做,您将获得exception。 这是一个例子(不是最好看,但它的工作原理):
static void Main(string[] args) { try { List stuff = new List (); int newStuff = 0; for (int i = 0; i < 10; i++) stuff.Add("."); Console.WriteLine("Doing ForEach()"); stuff.ForEach(delegate(string s) { Console.Write(s); if (++newStuff < 10) stuff.Add("+"); // This will work fine and you will continue to loop though it. }); Console.WriteLine(); Console.WriteLine("Doing foreach() { }"); newStuff = 0; foreach (string s in stuff) { Console.Write(s); if (++newStuff < 10) stuff.Add("*"); // This will cause an exception. } Console.WriteLine(); } catch { Console.WriteLine(); Console.WriteLine("Error!"); } Console.ReadLine(); }
它很可能更快 (你不应该只选择一个而不仅仅是因为它具有较小的性能优势,除非你正在处理计算量大的数字运算或图形应用程序而你需要从处理器周期中获得最大的收益)和您可以直接将代理传递给它,在某些情况下可能很方便:
list.ForEach(Console.WriteLine); // dumps the list to console.
对列表中的项执行操作是一种更方便的方式/简写, MoreLinq为实现IEnumerable的所有人扩展了此function。