为什么在lambda表达式中使用迭代变量是不好的 [英] Why is it bad to use an iteration variable in a lambda expression

查看:139
本文介绍了为什么在lambda表达式中使用迭代变量是不好的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是编写了一些快速代码并发现了这个编译器错误

I was just writing some quick code and noticed this complier error


在lambda表达式中使用迭代变量可能会产生意外结果。

相反,在循环中创建一个局部变量并为其赋值迭代变量的值。

Using the iteration variable in a lambda expression may have unexpected results.
Instead, create a local variable within the loop and assign it the value of the iteration variable.

I知道这意味着什么,我可以很容易地解决它,这不是什么大问题。

但是我想知道为什么在lambda中使用迭代变量是个坏主意?

什么我可以在以后引起问题吗?

I know what it means and I can easily fix it, not a big deal.
But I was wondering why it is a bad idea to use a iteration variable in a lambda?
What problems can I cause later on?

推荐答案

考虑以下代码:

List<Action> actions = new List<Action>();

for (int i = 0; i < 10; i++)
{
    actions.Add(() => Console.WriteLine(i));
}

foreach (Action action in actions)
{
    action();
}

您希望打印什么?显而易见的答案是0 ... 9 - 但实际上它打印10次,10次。这是因为只有一个变量被所有代表捕获。这种行为是出乎意料的。

What would you expect this to print? The obvious answer is 0...9 - but actually it prints 10, ten times. It's because there's just one variable which is captured by all the delegates. It's this kind of behaviour which is unexpected.

编辑:我刚刚看到你在谈论VB.NET而不是C#。我相信VB.NET有更复杂的规则,因为变量在迭代中保持其值的方式。 这篇文章作者:贾里德·帕森斯(Jared Parsons)提供了一些关于所涉及的困难的信息 - 虽然它是从2007年开始的,但实际行为可能已经发生了变化。

I've just seen that you're talking about VB.NET rather than C#. I believe VB.NET has even more complicated rules, due to the way variables maintain their values across iterations. This post by Jared Parsons gives some information about the kind of difficulties involved - although it's back from 2007, so the actual behaviour may have changed since then.

这篇关于为什么在lambda表达式中使用迭代变量是不好的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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