How to remove all event handlers from an event?

末鹿安然 提交于 2019-12-01 12:19:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/26576547/how-to-remove-all-event-handlers-from-an-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!