如何关闭的foreach和list.ForEach()之间有什么不同? [英] How do closures differ between foreach and list.ForEach()?
问题描述
考虑以下代码
VAR值=新的List< INT> {123,432,768};
变种funcs中=新名单<&Func键LT; INT>>();
values.ForEach(V => funcs.Add(()=> 5));
funcs.ForEach(F => Console.WriteLine(F())); //打印123432768
funcs.Clear();
的foreach(中值VAR V1)
{
funcs.Add(()=> V1);
}
的foreach(在funcs中VAR FUNC)
{
Console.WriteLine(FUNC()); //打印768768768
}
我知道,第二次的foreach打印768的3倍,因为被抓获的lambda关闭变量。为什么它不是在第一种情况下发生?如何的foreach
关键字从方法不同 Foreach源
?它是怎么一回事,因为表达式求值当我这样做 values.ForEach
的foreach
只介绍的有一个的变量。
与比较>
的foreach(中值VAR V1)// V1 * *相同变量中的每个循环,值改为
{
VAR freshV1 = V1; // freshV1是*新的*变量每次循环
funcs.Add(()=> freshV1);
}
的foreach(在funcs中VAR FUNC)
{
Console.WriteLine(FUNC()); //打印123432768
}
这就是
的foreach(T中配...){}
可以被认为是的:
T伏;
的foreach(V IN ...){}
编码愉快。
Consider this code.
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
}
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
only introduces one variable. While the lambda parameter variable is "fresh" each time it is invoked.
Compare with:
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
}
That is,
foreach (T v in ...) { }
can be thought of as:
T v;
foreach(v in ...) {}
Happy coding.
这篇关于如何关闭的foreach和list.ForEach()之间有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!