在 lambda 表达式中使用迭代变量可能会产生意外的结果。 相反,在循环内创建局部变量,并为其分配迭代变量的值。
在循环内声明的 lambda 表达式中使用循环迭代变量时,会出现此警告。 例如,以下示例将导致出现警告。
For i As Integer = 1 To 10
' The warning is given for the use of i.
Dim exampleFunc As Func(Of Integer) = Function() i
Next
以下示例显示可能会发生的意外结果。
Module Module1
Sub Main()
Dim array1 As Func(Of Integer)() = New Func(Of Integer)(4) {}
For i As Integer = 0 To 4
array1(i) = Function() i
Next
For Each funcElement In array1
System.Console.WriteLine(funcElement())
Next
End Sub
End Module
For
循环将创建 lambda 表达式的数组,其中每个表达式都返回循环迭代变量 i
的值。 在 For Each
循环中计算 lambda 表达式时,你可能希望看到显示 0、1、2、3 和 4,即 i
在 For
循环中连续出现的值。 但实际上,你会看到 i
的最终值显示五次:
5
5
5
5
5
默认情况下,此消息是一个警告。 有关隐藏警告或将警告视为错误的详细信息,请参阅 Configuring Warnings in Visual Basic。
错误 ID:BC42324
更正此错误
- 将迭代变量的值分配到局部变量,并在 lambda 表达式中使用该局部变量。
Module Module1
Sub Main()
Dim array1 As Func(Of Integer)() = New Func(Of Integer)(4) {}
For i As Integer = 0 To 4
Dim j = i
array1(i) = Function() j
Next
For Each funcElement In array1
System.Console.WriteLine(funcElement())
Next
End Sub
End Module