Reputation: 5968
I have the following class
Public Class SimpleClass
Public Event SimpleEvent()
Public Sub SimpleMethod()
RaiseEvent SimpleEvent()
End Sub
End Class
I instanciate it like
Obj = New SimpleClass
AddHandler Obj.SimpleEvent, Sub()
MsgBox("Hi !")
End Sub
And i'm trying to remove the event handler dynamically-created using the code in : Code Project
(I assume a complex application where it's difficult to use : RemoveHandler Obj.Event, AddressOf Me.EventHandler)
In their code there is the following method
Private Shared Sub BuildEventFields(t As Type, lst As List(Of FieldInfo))
For Each ei As EventInfo In t.GetEvents(AllBindings)
Dim dt As Type = ei.DeclaringType
Dim fi As FieldInfo = dt.GetField(ei.Name, AllBindings)
If fi IsNot Nothing Then
lst.Add(fi)
End If
Next
End Sub
But when calling this code using my object type, the next line returns nothing
Dim fi As FieldInfo = dt.GetField(ei.Name, AllBindings)
means that somehow my event is not recognized as a field.
Does anyone know how to remove all event handlers from an event ?
Cheers in advance.
Upvotes: 0
Views: 1888
Reputation: 941455
It is the lambda expression that is getting you into trouble here. Don't dig a deeper hole, just use AddressOf and a private method instead so you can trivially use the RemoveHandler statement.
If you absolutely have to then keep in mind that the VB.NET compiler auto-generates a backing store field for the event with the same name as the event with "Event" appended. Which makes this code work:
Dim Obj = New SimpleClass
AddHandler Obj.SimpleEvent, Sub()
MsgBox("Hi !")
End Sub
Dim fi = GetType(SimpleClass).GetField("SimpleEventEvent", BindingFlags.NonPublic Or BindingFlags.Instance)
fi.SetValue(Obj, Nothing)
Obj.SimpleMethod() '' No message box
I'll reiterate that you should not do this.
Upvotes: 4