【发布时间】:2012-04-10 01:30:25
【问题描述】:
可能重复:
Is there a reason for C#'s reuse of the variable in a foreach?
Looping through a list of Actions
今天我遇到了一个关于 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。为什么?我只是无法理解。问了一些人,他们只是说这段代码中有闭包,但是我不是很清楚,我记得在javascript中我经常遇到闭包,但是在上面的代码中,为什么会有闭包?谢谢。
【问题讨论】:
-
这个问题几乎每天都会被问到。请参阅stackoverflow.com/questions/8898925/… 以获得对该问题的良好讨论。