C#:列表中任何好处; T> .ForEach(...)通过纯foreach循环? [英] C#: Any benefit of List<T>.ForEach(...) over plain foreach loop?

查看:67
本文介绍了C#:列表中任何好处; T> .ForEach(...)通过纯foreach循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么列表< T> .ForEach(动作< T>)。存在

有没有做任何好处/差异:

Is there any benefit/difference in doing :

elements.ForEach(delegate(Element element){ element.DoSomething(); });



over

foreach(Element element in elements) { element.DoSomething();}

推荐答案

一个关键的区别是与.ForEach方法可以修改底层集合。随着在foreach语法,如果你这样做,你会得到一个异常。这里是一个例子(不正是最好看的,但它的工作原理):

One key difference is with the .ForEach method you can modify the underlying collection. With the foreach syntax you'll get an exception if you do that. Here's an example of that (not exactly the best looking but it works):

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();
}

这篇关于C#:列表中任何好处; T&GT; .ForEach(...)通过纯foreach循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆