可能重复:
为什么在 lambda 表达式中使用迭代变量是不好的?
为什么会出现“在 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
基本上什么都没有改变,除了警告消失了。我只是让另一个变量指向我的变量。为什么会有警告?可能会发生哪些意外情况?