ラムダ式は、このイベント ハンドラーから削除されません。 ラムダ式を変数に割り当て、変数を使用してイベントを追加および削除します。
ラムダ式をイベント ハンドラーと共に使用すると、予期した動作が表示されないことがあります。 コンパイラは、ラムダ式定義が同一であっても、各ラムダ式定義に対して新しいメソッドを生成します。 したがって、次のコードは 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
このエラーを解決するには
警告を回避してラムダ式を削除するには、次の例に示すように、ラムダ式を変数に割り当て、 AddHandler ステートメントと RemoveHandler ステートメントの両方で変数を使用します。
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 にあります。そこで、issue や pull request を作成および確認することもできます。 詳細については、共同作成者ガイドを参照してください。
.NET