问题描述
我遇到了一个关于 C# 的有趣问题.我有如下代码.
I met an interesting issue about C#. I have code like below.
List<Func<int>> actions = new List<Func<int>>();
int variable = 0;
while (variable < 5)
{
actions.Add(() => variable * 2);
++ variable;
}
foreach (var act in actions)
{
Console.WriteLine(act.Invoke());
}
我希望它输出 0、2、4、6、8.然而,它实际上输出了五个 10.
I expect it to output 0, 2, 4, 6, 8. However, it actually outputs five 10s.
这似乎是由于所有操作都引用了一个捕获的变量.因此,当它们被调用时,它们都有相同的输出.
It seems that it is due to all actions referring to one captured variable. As a result, when they get invoked, they all have same output.
有没有办法绕过这个限制,让每个动作实例都有自己的捕获变量?
Is there a way to work round this limit to have each action instance have its own captured variable?
推荐答案
是的 - 在循环内获取变量的副本:
Yes - take a copy of the variable inside the loop:
while (variable < 5)
{
int copy = variable;
actions.Add(() => copy * 2);
++ variable;
}
您可以将其想象为 C# 编译器每次遇到变量声明时都会创建一个新"局部变量.事实上,它会创建适当的新闭包对象,如果您在多个范围内引用变量,它会变得复杂(在实现方面),但它可以工作:)
You can think of it as if the C# compiler creates a "new" local variable every time it hits the variable declaration. In fact it'll create appropriate new closure objects, and it gets complicated (in terms of implementation) if you refer to variables in multiple scopes, but it works :)
请注意,此问题更常见的情况是使用 for
或 foreach
:
Note that a more common occurrence of this problem is using for
or foreach
:
for (int i=0; i < 10; i++) // Just one variable
foreach (string x in foo) // And again, despite how it reads out loud
有关更多详细信息,请参阅 C# 3.0 规范的第 7.14.4.2 节,以及我的 文章闭包还有更多的例子.
See section 7.14.4.2 of the C# 3.0 spec for more details of this, and my article on closures has more examples too.
请注意,从 C# 5 及更高版本开始(即使指定了早期版本的 C#),foreach
的行为发生了变化,因此您不再需要制作本地副本.请参阅 此回答了解更多详情.
Note that as of the C# 5 compiler and beyond (even when specifying an earlier version of C#), the behavior of foreach
changed so you no longer need to make local copy. See this answer for more details.
这篇关于在 C# 的循环中捕获的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!