在 C# 中的循环中捕获变量 [英] Captured variable in a loop in C#

查看:30
本文介绍了在 C# 中的循环中捕获变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个关于 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.然而,它实际上输出了 5 个 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 :)

请注意,此问题更常见的情况是使用 forforeach:

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# 中的循环中捕获变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆