我在捕获的变量中遇到了这种奇怪的行为。下面是两个循环。我希望两者都表现得一样。为什么表现不同?
private static void Loop1()
{
var actions = new List<Action>();
foreach (var number in Enumerable.Range(1, 5))
{
actions.Add(()=>Console.WriteLine(number));
}
foreach (var currentAction in actions)
{
currentAction();
}
}
private static void Loop2()
{
var actions = new List<Action>();
for (int number = 0; number <= 4; number++)
{
actions.Add(() => Console.WriteLine(number));
}
foreach (var currentAction in actions)
{
currentAction();
}
}
第一个循环打印1,2,3,4,5 第二个循环打印5,5,5,5,5