람다 식은 이 이벤트 처리기에서 제거되지 않습니다. 변수에 람다 식을 할당하고 변수를 사용하여 이벤트를 추가하고 제거합니다.
이벤트 처리기와 함께 람다 식을 사용하는 경우 예상되는 동작이 표시되지 않을 수 있습니다. 컴파일러는 동일한 경우에도 각 람다 식 정의에 대해 새 메서드를 생성합니다. 따라서 다음 코드가 표시됩니다.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
이벤트 처리기와 함께 람다 식을 사용하면 예기치 않은 결과가 발생할 수 있습니다. 다음 예제에서는 추가 AddHandler 된 람다 식이 문에 의해 RemoveHandler 제거되지 않습니다.
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
기본적으로 이 메시지는 경고입니다. 경고를 숨기거나 경고를 오류로 처리하는 방법에 대한 자세한 내용은 Visual Basic에서 경고 구성을 참조하세요.
오류 ID: BC42326
이 오류를 해결하려면
경고를 방지하고 람다 식을 제거하려면 다음 예제와 같이 변수에 람다 식을 할당하고 변수와 RemoveHandler 문 모두에서 AddHandler 변수를 사용합니다.
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
참고하십시오
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET