これは深刻なリファクタリングを必要としますが、うまく機能するようになりました。
匿名メソッドをイベントのダイレクトイベントハンドラとして使用します。このメソッドは、イベントの名前と実際のハンドラを取得し、別のプロキシイベントハンドラに渡します。そのプロキシは実際のハンドラを呼び出し、キャプチャされたイベントの名前を渡します。
Imports System.Reflection
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim list As New List(Of HandlerInfo)
list.Add(New HandlerInfo() With {.EventName = "Click", .HandlerName = "mysub"})
list.Add(New HandlerInfo() With {.EventName = "MouseEnter", .HandlerName = "mysub"})
list.Add(New HandlerInfo() With {.EventName = "MouseLeave", .HandlerName = "mysub"})
For Each info As HandlerInfo In list
Dim eventName As String = info.EventName 'Use local variables, rather that the iterator, or else the wrong object will get captured and it won't work correctly.
Dim handlerName As String = info.HandlerName
Dim dynamicEventInfo As EventInfo = Button1.GetType.GetEvent(eventName)
dynamicEventInfo.AddEventHandler(Button1, New EventHandler(Sub(sender2 As Object, e2 As EventArgs)
Dim t As Type = GetType(Form1) 'This is the type of the object that contains the handler
Dim i As Object = Me 'This is the instance of "t" that the handler should be invoked on
Dim handler As MethodInfo = t.GetMethod(handlerName)
handler.Invoke(i, New Object() {sender2, e2, eventName})
End Sub))
Next
End Sub
Private Class HandlerInfo
Public Property EventName As String
Public Property HandlerName As String
End Class
Public Sub mysub(sender As Object, e As EventArgs, eventName As String)
Debug.WriteLine(eventName)
End Sub
End Class
これは「A/B問題」と思われます。あなたはなぜこれを行う必要があるかについて私たちにもっと教えていただけますか? –
私のアプリケーションの中では、イベントとメソッドは設定ファイルと一緒に保存されます。したがって、私は実行時にどの組み合わせが設定されているかわかりません。同じオブジェクトが同じメソッドを2回含んでいて、異なるイベントを使用している(つまり、入力して離れる)場合は、メソッドを呼び出すイベントがわからないと、辞書に格納された特定のメソッドのパラメータを取得できません。 thur for ur help – skrskr
問題は、メソッドの名前とイベントの名前と、そのメソッドを使って前記イベントを処理する方法と、メソッド内でどのイベントが発生したかを何らかの形で知ることである。これは正しいです? – djv