如何从事件中删除所有事件处理程序? [英] How to remove all event handlers from an event?

查看:42
本文介绍了如何从事件中删除所有事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程

Public Class SimpleClass
    Public Event SimpleEvent()

    Public Sub SimpleMethod()
        RaiseEvent SimpleEvent()
    End Sub
End Class

我把它实例化

    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

(我假设一个复杂的应用程序很难使用:RemoveHandler Obj.Event, AddressOf Me.EventHandler)

(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 ?

提前干杯.

推荐答案

这里是 lambda 表达式让您陷入困境.不要深挖,只需使用 AddressOf 和私有方法,这样您就可以轻松使用 RemoveHandler 语句.

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.

如果您绝对必须记住,VB.NET 编译器会自动为事件生成一个后备存储字段,该字段与附加了事件"的事件同名.这使此代码工作:

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.

这篇关于如何从事件中删除所有事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆