gpt4 book ai didi

.net - 为什么我得到 : "iteration variable in a lambda expression may have unexpected results"

转载 作者:行者123 更新时间:2023-12-03 18:20:12 27 4
gpt4 key购买 nike

这个问题在这里已经有了答案:




10年前关闭。




Possible Duplicate:
Why is it bad to use a iteration variable in a lambda expression



为什么我会得到:“lambda 表达式中的迭代变量可能会产生意外结果”?假设我有以下代码:
  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

我收到警告:
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.

我不明白为什么将我的代码更改为以下内容会发生任何变化:
  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

除了警告消失之外,基本上没有任何变化。我只有另一个变量指向我的变量。为什么要发出警告?可能会发生什么意想不到的事情?

最佳答案

lambda 绑定(bind)到变量,而不是绑定(bind)到 lambda 转换为委托(delegate)时变量所具有的值。随着循环变量的更新,每个创建的绑定(bind)到该变量的 lambda 也会看到变量的更改值,这是您可能不想要的。每次迭代循环时创建一个新变量会将每个 lambda 绑定(bind)到一个新的、不同的、不变的变量上。

这是 C# 和 VB 的主要痛点。 在 C# 5 和 VB 11 中,我们正在更改循环闭包语义以缓解此问题。

有关更多信息,请参阅

Is there a reason for C#'s reuse of the variable in a foreach?

以及蒂姆文章的最后几段:

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

和我的文章:

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

关于.net - 为什么我得到 : "iteration variable in a lambda expression may have unexpected results",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9524041/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com