gpt4 book ai didi

c# 在 Lambda 表达式中声明变量

转载 作者:可可西里 更新时间:2023-11-01 08:42:59 25 4
gpt4 key购买 nike

以下代码输出 33 而不是 012。我不明白为什么在每次迭代中都没有捕获新变量 loopScopedi 而不是捕获相同的变量。

Action[] actions = new Action[3];

for (int i = 0; i < 3; i++)
{

actions [i] = () => {int loopScopedi = i; Console.Write (loopScopedi);};
}

foreach (Action a in actions) a(); // 333

Hopwever,这段代码产生了012,两者有什么区别?

Action[] actions = new Action[3];

for (int i = 0; i < 3; i++)
{
int loopScopedi = i;
actions [i] = () => Console.Write (loopScopedi);
}

foreach (Action a in actions) a(); // 012

最佳答案

这称为“访问修改后的闭包”。基本上,只有一个 i 变量,所有三个 lambda 都引用它。最后,i 变量增加到 3,因此所有三个操作都打印 3。 (请注意,lambda 中的 int loopScopedi = i 仅在您稍后调用 lambda 时运行。)

在第二个版本中,您为每次迭代创建一个新的 int loopScopedi,并将其设置为 i 的当前值,即 012,对于每次迭代。

您可以尝试想象内联 lambda 以更清楚地看到发生了什么:

foreach (Action a in actions)
{
int loopScopedi = i; // i == 3, since this is after the for loop
Console.Write(loopScopedi); // always outputs 3
}

对比:

foreach (Action a in actions)
{
// normally you could not refer to loopScopedi here, but the lambda lets you
// you have "captured" a reference to the loopScopedi variables in the lambda
// there are three loopScopedis that each saved a different value of i
// at the time that it was allocated
Console.Write(loopScopedi); // outputs 0, 1, 2
}

关于c# 在 Lambda 表达式中声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16801896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com