[询问]无法引发活动 [英] [Ask] Can not raise an event
问题描述
我正在尝试学习一个事件.但是,它不能按预期提高.这是代码.请告诉我要更改的地方.提前谢谢.
Hi, I''m trying to learn an event. However, it can''t raise as expected. Here''s the code. Please tell me where to change. Thanks in advance.
Public Class Executor
Public Sub New()
TryChange()
End Sub
Public Sub New(ByVal value As String)
TryChange(value)
End Sub
Public Delegate Sub ExecutorChangeEventHandler(ByVal sender As Object, ByVal e As ExecutorChangeEventArgs)
Public Event Change As ExecutorChangeEventHandler
Protected Overridable Sub OnChange(ByVal e As ExecutorChangeEventArgs)
If Not IsNothing(e) Then
RaiseEvent Change(Me, e)
End If
End Sub
Public Sub TryChange()
OnChange(New ExecutorChangeEventArgs)
End Sub
Public Sub TryChange(ByVal value As String)
Dim e As New ExecutorChangeEventArgs
e.ValueToChange = value
OnChange(e)
End Sub
End Class
Public Class ExecutorChangeEventArgs
Inherits EventArgs
Protected _values As String = "I LOVE YOU"
Public Property ValueToChange As String
Get
Return _values
End Get
Set(ByVal value As String)
_values = value
End Set
End Property
Public ReadOnly Property Changed As Boolean
Get
If ValueToChange <> "I LOVE YOU" Then
Return True
Else
Return False
End If
End Get
End Property
End Class
这是我添加事件的位置(单击按钮)
Here is where I add the event (on button click)
Private Sub btn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim ex As New Executor()
ex.TryChange()
AddHandler ex.Change, New Executor.ExecutorChangeEventHandler(AddressOf executor_Change)
End Sub
Private Sub executor_Change(ByVal sender As Object, ByVal e As ExecutorChangeEventArgs)
MessageBox.Show(e.Changed.ToString)
End Sub
当我单击按钮时,它什么也没显示.如您所见,它的MessageBox.Show.请帮助我.
When I click the button, it shows nothing. As you see ther''s MessageBox.Show. Help me please.
推荐答案
启动事件后,您将尝试处理该事件.
尝试将btn单击更改为:
Hi,
You are trying to handle the event after you have initiated it.
try changing the btn click to this:
Private Sub btn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim ex As New Executor()
AddHandler ex.Change, New Executor.ExecutorChangeEventHandler(AddressOf executor_Change)
ex.TryChange()
End Sub
您可能遇到的另一个问题是,您将在按钮单击中实例化Executor的新实例.到事件被调用时,执行者对象将无法引用,因为它仅在单击按钮的范围内.您应该考虑将ex(Executor)移到类级别的私有声明中,以便在类对象的生存期内可用.
即
The other issue you have (possibly) is that you are instantiating a new instance of Executor in the button click. By the time the event is called the executor object will not be avaliable to reference back as it was only in the scope of the button click. You should consider moving the ex (Executor) to a private declaration at class level so that it is avalaible for the lifetime of the class object.
i.e.
private ex as Executor
public sub new()
ex = new Executor
AddHandler ex.Change, New Executor.ExecutorChangeEventHandler(AddressOf executor_Change)
end sub
Private Sub btn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
ex.TryChange()
End Sub
这篇关于[询问]无法引发活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!