从类内部找出事件处理程序是否存在于另一个类中



一个VB。. NET 4问题

让我们假设存在一个类a,它包含一个事件e。在另一个类(B)中,a类型的变量声明为WithEvents。在a代码的某一点上,将会有一个"RaiseEvent";命令。之后,是否有一种方法知道E是否在B中被处理(只是如果事件E的处理程序存在于B类中)?

显然E可以包含一个参数(即布尔值),这样如果B中的处理程序处理它,它可以将该参数设置为True。但这不是我要问的。我想知道是否有一个内置到。. NET方法来实现这一点,而不使用任何参数。

我试图避免的代码示例(使用参数DoSomethingWasHandled):

Public Class A
Public Event DoSomething(ByRef DoSomethingWasHandled As Boolean)

Public Sub RaiseDoSomething()
Dim DoSomethingWasHandled As Boolean = False
RaiseEvent DoSomething(DoSomethingWasHandled)
End Sub
End Class

Public Class B
Public WithEvents SomeA As New A

Private Sub HandleDoSomething(ByRef DoSomethingWasHandled As Boolean) Handles SomeA.DoSomething
DoSomethingWasHandled = True
End Sub
End Class

我问它是否存在的代码示例:

Public Class A
Public Event DoSomething()

Public Sub RaiseDoSomething()
RaiseEvent DoSomething()
If DoSomething.WasHandled Then '<-- Does this check exist in any form? ***
DoSomethingElse()
End If
End Sub
End Class

Public Class B
Public WithEvents SomeA As New A

Private Sub HandleDoSomething() Handles SomeA.DoSomething
'DoStuff...
End Sub
End Class

***这只会检查类B中是否存在E的事件处理程序,如果存在则返回True,如果不存在则返回False。

像这样

Public Class A
Public Event DoSomething(e As Object)
Public Sub RaiseDoSomething()
' adding 'Event' to the variable name of
'  the event allows it to be checked
If DoSomethingEvent IsNot Nothing Then 'does the event have a subscriber(Event Handler)?
'yes
RaiseEvent DoSomething("TEST") 'because there is a handler this will be handled
End If
End Sub
End Class
Public Class B
Public WithEvents SomeA As New A
Private Sub HandleDoSomething(e As Object) Handles SomeA.DoSomething
Debug.WriteLine("Do")
End Sub
End Class

测试
Dim FOOa As New A
Dim fooB As New B
FOOa.RaiseDoSomething()
fooB.SomeA.RaiseDoSomething()

相关内容

最新更新