当你捕捉一个迭代变量for循环,C#把那个变量,就好像它是在循环外声明。这意味着相同的变量被捕获在每个迭代。下面的程序写的,而不是写012 333:
When you capture the iteration variable of a for loop, C# treats that variable as though it was declared outside the loop. This means that the same variable is captured in each iteration. The following program writes 333 instead of writing 012:
Action[] actions = new Action[3];
for (int i = 0; i < 3; i++)
actions [i] = () => Console.Write (i);
foreach (Action a in actions) a(); // 333
我读果壳中的(第5版)C#,今天我遇到了这一点,但我不能让我的头了吧,我不知道为什么输出 333
,而不是 012
。是不是因为我
这是越来越打印的值是在的值的的循环?这怎么可能? 我
应该是设置在循环结束后,是不是?
I'm reading C# in a Nutshell (5th Edition) and today i came across this but i can't get my head over it, i don't get why the output is 333
and not 012
. Is it because the value of i
that's getting printed is the value after the loop? How is that possible? i
is supposed to be disposed after the loop, isn't it?
变量我
被捕捉在为
循环,但你的善良这样做扩大了它的范围。因此,留在它的变量为3最后的状态,因此code输出333。
The variable i
is captured inside the for
loop but your are kind of extending the scope of it by doing so. So the variable is left at it's last state which was 3, hence the code outputting 333.
另一种方式来写code是这样的:
Another way to write the code is this:
Action[] actions = new Action[3];
int i; //declare i here instead of in the for loop
for (i = 0; i < 3; i++)
actions [i] = () => Console.Write (i);
//Now i=3
foreach (Action a in actions) a(); // 333
输出是一样的写法:
The output is the same as writing:
Console.Write(i);
Console.Write(i);
Console.Write(i);