C#:与普通 foreach 循环相比,List<T>.ForEach(...) 有什么好处? [英] C#: Any benefit of List<T>.ForEach(...) over plain foreach loop?

查看:27
本文介绍了C#:与普通 foreach 循环相比,List<T>.ForEach(...) 有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么 List.ForEach(Action) 存在.

I'm wondering why List<T>.ForEach(Action<T>) exists.

这样做是否有任何好处/差异:

Is there any benefit/difference in doing :

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

结束

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#:与普通 foreach 循环相比,List&lt;T&gt;.ForEach(...) 有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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