foreach 和 list.ForEach() 之间的闭包有何不同? [英] How do closures differ between foreach and list.ForEach()?

查看:25
本文介绍了foreach 和 list.ForEach() 之间的闭包有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个代码.

        var values = new List<int> {123, 432, 768};

        var funcs = new List<Func<int>>();

        values.ForEach(v=>funcs.Add(()=>v));

        funcs.ForEach(f=>Console.WriteLine(f()));//prints 123,432,768

        funcs.Clear();

        foreach (var v1 in values)
        {
            funcs.Add(()=>v1);
        }

        foreach (var func in funcs)
        {
            Console.WriteLine(func());  //prints 768,768,768
        } 

我知道第二个 foreach 打印 768 3 次,因为 lambda 捕获了闭包变量.为什么在第一种情况下不会发生? foreach 关键字与方法 Foreach 有何不同?是因为当我执行 values.ForEach

I know that the second foreach prints 768 3 times because of the closure variable captured by the lambda. why does it not happen in the first case?How does foreach keyword different from the method Foreach? Is it beacuse the expression is evaluated when i do values.ForEach

推荐答案

foreach 只引入一个变量.而 lambda 参数变量每次被调用时都是新鲜的".

foreach only introduces one variable. While the lambda parameter variable is "fresh" each time it is invoked.

比较:

foreach (var v1 in values) // v1 *same* variable each loop, value changed
{
   var freshV1 = v1; // freshV1 is *new* variable each loop
   funcs.Add(() => freshV1);
} 

foreach (var func in funcs)
{
   Console.WriteLine(func()); //prints 123,432,768
}

也就是说,

foreach (T v in ...) { }

可以理解为:

T v;
foreach(v in ...) {}

快乐编码.

这篇关于foreach 和 list.ForEach() 之间的闭包有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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