可能重复:
Is there a reason for C#'s reuse of the variable in a foreach?
Looping through a list of ActionsC#关闭工程?
今天我遇到一个关于C#的foreach功能的问题,它并没有给我正确的结果如我所料。这里是代码:
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] data = new int[] { 1, 2, 3, 4, 5 };
List<Func<int>> actions = new List<Func<int>>();
foreach (int x in data)
{
actions.Add(delegate() { return x; });
}
foreach (var foo in actions)
{
Console.WriteLine(foo());
}
Console.ReadKey();
}
}
}
,当我在控制台应用程序运行它,它可以打印在屏幕上5个5。为什么?我只是不明白。有人问过一些人,他们只是说这个代码有闭包,但我对此不是很清楚,我记得在javascript中,我经常遇到闭包,但在上面的代码中,为什么会有闭包?谢谢。
查看:http://stackoverflow.com/questions/9569334/looping-through-a-list -of-actions/ – 2012-03-26 14:23:31
http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx – 2012-03-26 14:24:43
几乎每个人都会问这个问题天。请参阅http://stackoverflow.com/questions/8898925/is-there-a-reason-for-cs-reuse-of-the-variable-in-a-foreach/8899347#8899347了解有关此问题的良好讨论。 – 2012-03-26 14:47:45