可能重複:
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