How to remove all event handlers from an event?

后端 未结 1 1729
一生所求
一生所求 2021-01-17 01:12

I have the following class

Public Class SimpleClass
    Public Event SimpleEvent()

    Public Sub SimpleMethod()
        RaiseEvent SimpleEvent()
    End S         


        
相关标签:
1条回答
  • 2021-01-17 02:13

    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.

    0 讨论(0)
提交回复
热议问题