外生变量的陷阱 [英] Outer Variable Trap

查看:195
本文介绍了外生变量的陷阱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

究竟是外生变量的陷阱?
解释和实例在C#中的AP preciated。

What exactly is the Outer Variable Trap? Explanation and examples in C# are appreciated.

编辑:合并乔恩斯基特的发号施令:)

Incorporating Jon Skeet's diktat :)

<一个href=\"http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx\">Eric利珀特的外生变量的陷阱

推荐答案

当开发人员需要一个变量的值由一个lambda前pression或匿名委托,实际上当被捕获的外生变量的陷阱的发生变量被捕获本身

The "Outer Variable Trap" occurs when a developer expects the value of a variable to be captured by a lambda expression or anonymous delegate, when actually the variable is captured itself.

示例:

var actions = new List<Action>();
for (var i = 0; i < 10; i++)
{
    actions.Add(() => Console.Write("{0} ", i));
}
foreach (var action in actions)
{
    action();
}

可能的输出#1:

0 1 2 3 4 5 6 7 8 9

可能的输出#2:

10 10 10 10 10 10 10 10 10 10

如果您期望输出#1,你已经掉进了外生变量的陷阱。你得到的输出#2。

If you expected output #1, you've fallen into the Outer Variable Trap. You get output #2.

修正:

声明一个内部变量被重复拍摄的,而不是用来捕捉只有一次的外生变量。

Declare an "Inner Variable" to be captured repeatedly instead of the "Outer Variable" which is captured only once.

var actions = new List<Action>();
for (var i = 0; i < 10; i++)
{
    var j = i;
    actions.Add(() => Console.Write("{0} ", j));
}
foreach (var action in actions)
{
    action();
}

有关详细信息,参见<一个href=\"http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx\">Eric利珀特的博客。

这篇关于外生变量的陷阱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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