BC42324:在 Lambda 運算式中使用反覆項目變數可能會產生非預期的結果

在 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,也就是 For 迴圈中的 i 後續值。 然而,您會看到 i 的最後值顯示五次:

5

5

5

5

5

根據預設,這個訊息是一個警告。 如需隱藏警告或將警告視為錯誤的詳細資訊,請參閱 Configuring Warnings in Visual Basic

錯誤識別碼: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

另請參閱