为什么我得到:"在一个lambda EX pression迭代变量可能会有意想不到的效果" [英] Why do I get: "iteration variable in a lambda expression may have unexpected results"

查看:162
本文介绍了为什么我得到:"在一个lambda EX pression迭代变量可能会有意想不到的效果"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/227820/why-is-it-bad-to-use-a-iteration-variable-in-a-lambda-ex$p$pssion">Why它是坏到一个lambda EX pression使用迭代变量

为什么我得到:在一个lambda EX pression迭代变量可能会有意想不到的效果?假设我有以下的code:

Why do I get: "iteration variable in a lambda expression may have unexpected results"? Suppose I have the following code:

  Dim writeAbleColumns As String() = {"IsSelected", "IsFeeExpense", "IsSubscriptionRedemption"}
  With grid
     For Each column As DataGridViewColumn In .Columns
      column.ReadOnly = Not Array.Exists(writeAbleColumns, Function(arrElement) column.Name = arrElement)
      Next
  End With

我得到警告:

I get the warning:

Warning 1   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.

我不明白为什么改变我的code到以下更改什么:

I don't understand why changing my code to the following changes anything:

  Dim writeAbleColumns As String() = {"IsSelected", "IsFeeExpense", "IsSubscriptionRedemption"}
  With grid
     For Each column As DataGridViewColumn In .Columns
      Dim c As DataGridViewColumn = column
      column.ReadOnly = Not Array.Exists(writeAbleColumns, Function(arrElement) c.Name = arrElement)
      Next
  End With

从根本上没有什么变化,除了警告消失。我只是另一个变量指向我的变量。为什么报警?可能会发生什么意想不到的事情?

Fundamentally nothing changes except the warning disappears. I just have another variable point to my variable. Why the warning? What unexpected things might happen?

推荐答案

将拉姆达势必会的变量的,不要的的变量有当拉姆达变成了代表的价值的。随着循环变量更新的每个拉姆达创建绑定到该变量的也看到了变数,你可能不希望的更改的值。创建每次迭代循环时间超过一个新的,不同的,不变的变量绑定每个拉姆达一个新的变量。

The lambda is bound to the variable, not to the value the variable had when the lambda was turned into a delegate. As the loop variable updates, every lambda created bound to that variable also sees the changed value of the variable, which you might not want. Creating a new variable every time you iterate the loop binds each lambda over a new, different, unchanging variable.

这是在C#和VB的主要痛点。 在C#5和VB 11,我们正在改变环闭合语义来缓解这个问题。

This is a major pain point in C# and VB. In C# 5 and VB 11 we are changing the loop closure semantics to mitigate this problem.

有关详细信息,请参阅

<一个href="http://stackoverflow.com/questions/8898925/is-there-a-reason-for-cs-reuse-of-the-variable-in-a-foreach/8899347#8899347">Is还有一个原因是C#的再利用在foreach的变量?

和蒂姆的文章的最后几段:

and the last few paragraphs of Tim's article:

http://msdn.microsoft.com/en-us/magazine/ cc163362.aspx

和我的文章:

http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/

这篇关于为什么我得到:&QUOT;在一个lambda EX pression迭代变量可能会有意想不到的效果&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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