Victor Anzala Victor Anzala - 1 month ago 8
Vb.net Question

Get AddressOf from MethodInfo object

I have labels that I created programmatically and want to give specific event handlers to each one. So, Instead of doing this:

AddHandler Label1.Click, AddressOf SomeSub1
AddHandler Label2.Click, AddressOf SomeSub2
AddHandler Label3.Click, AddressOf SomeSub3
...


I was hoping to work it into a loop to avoid the above. So I made:


  • A List of Labels

  • A MethodInfo array of all my already built, Private Subs in a class that is inherits from the main class where the labels are



I used the above and came up with the following:

Dim separateClass As New SeparateClass
Dim methodInfo() As MethodInfo = separateClass.GetType.GetMethods(BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.DeclaredOnly)

For i As Integer = 0 to End
labelList.Add(New Label())
AddHandler labelList.Last.Click, AddressOf [Delegate].CreateDelegate(GetType(SomeDelegate), separateClass, methodInfo(i)).GetMethodInfo
Next


And this does compile but the Subs aren't being triggered. The following also compiles but behaves the same way:

For i As Integer = 0 to End
labelList.Add(New Label())
AddHandler labelList.Last.Click, AddressOf methodInfo(i).getBaseDefinition
Next


Is there a way I can get the appropriate
AddressOf
out of a
MethodInfo
object?

Answer

[Delegate].CreateDelegate already creates a delegate object; you should not use AddressOf.

You may need to cast it, though.

Comments