外部变量陷阱 [英] Outer Variable Trap

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

问题描述

外部变量陷阱究竟是什么?感谢 C# 中的解释和示例.

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

合并 Jon Skeet 的命令 :)

Incorporating Jon Skeet's diktat :)

埃里克·利珀特关于外部变量陷阱

推荐答案

外变量陷阱"当开发人员希望 lambda 表达式或匿名委托捕获变量的值时发生,而实际上该变量本身被捕获.

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();
}

有关更多详细信息,另请参阅Eric Lippert 的博客.

For more details, see also Eric Lippert's blog.

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

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