[英].Net - When is List<T>.ForEach prefered over a standard foreach loop?
[英]C#: Any benefit of List<T>.ForEach(…) over plain foreach loop?
我想知道为什么List<T>.ForEach(Action<T>)
存在。
这样做有什么好处/差别:
elements.ForEach(delegate(Element element){ element.DoSomething(); });
过度
foreach(Element element in elements) { element.DoSomething();}
?
一个关键的区别是.ForEach方法可以修改底层集合。 使用foreach语法,如果这样做,您将获得异常。 这是一个例子(不是最好看,但它的工作原理):
static void Main(string[] args) {
try {
List<string> stuff = new List<string>();
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的人扩展了此功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.