BC42326:将不会从此事件处理程序中移除 Lambda 表达式

将不会从此事件处理程序中移除 Lambda 表达式。 向变量赋予 lambda 表达式,并使用该变量来添加和删除事件。

对于事件处理程序使用 lambda 表达式时,可能看不到预期的行为。 编译器会为每个 lambda 表达式定义生成一个新方法,即使表达式完全相同亦不例外。 因此,以下代码将显示 False

Module Module1

    Sub Main()
        Dim fun1 As ChangeInteger = Function(p As Integer) p + 1
        Dim fun2 As ChangeInteger = Function(p As Integer) p + 1
        Console.WriteLine(fun1 = fun2)
    End Sub

    Delegate Function ChangeInteger(ByVal x As Integer) As Integer

End Module

对于事件处理程序使用 lambda 表达式时,这可能会导致意外结果。 在以下示例中,RemoveHandler 语句不会删除通过 AddHandler 添加的 lambda 表达式。

Module Module1

    Event ProcessInteger(ByVal x As Integer)

    Sub Main()

        ' The following line adds one listener to the event.
        AddHandler ProcessInteger, Function(m As Integer) m

        ' The following statement searches the current listeners
        ' for a match to remove. However, this lambda is not the same
        ' as the previous one, so nothing is removed.
        RemoveHandler ProcessInteger, Function(m As Integer) m

    End Sub
End Module

默认情况下,此消息是一个警告。 有关如何隐藏警告或将警告视为错误的详细信息,请参阅 Configuring Warnings in Visual Basic

错误 ID:BC42326

更正此错误

若要避免此警告并删除 lambda 表达式,请将 lambda 表达式赋给一个变量,并在 AddHandlerRemoveHandler 语句中使用该变量,如下例中所示。

Module Module1

    Event ProcessInteger(ByVal x As Integer)

    Dim PrintHandler As ProcessIntegerEventHandler

    Sub Main()

        ' Assign the lambda expression to a variable.
        PrintHandler = Function(m As Integer) m

        ' Use the variable to add the listener.
        AddHandler ProcessInteger, PrintHandler

        ' Use the variable again when you want to remove the listener.
        RemoveHandler ProcessInteger, PrintHandler

    End Sub
End Module

请参阅