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

查看:30
本文介绍了为什么在 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.

我知道这意味着什么,我可以轻松修复它,没什么大不了的.
但我想知道为什么在 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天全站免登陆