看一个关于VB.NET编程的例子,在这里呢我使用另一种方法来说明当你建立和注册一个事件处理程序时到底发生了什么事情。一旦你明白事情是怎么回事,你也许会感激使用了更简洁的语法实现了相同的目标,一起来看看吧:
'建立银行帐号对象
Dim account1 As New BankAccount()
'注册事件处理程序
AddHandler account1.LargeWithdraw, AddressOf AccountHandlers.LogWithdraw
AddHandler account1.LargeWithdraw, AddressOf AccountHandlers.GetApproval
- 1.
- 2.
- 3.
- 4.
- 5.
因为AddHandler语句期待一个委托对象作为第二个参数,你能使用速记语法--AddressOf操作符后紧跟目标处理方法的名字。当Visual Basic .NET编译器看到该语法时,它接着产生额外的代码来建立作为事件处理程序服务的委托对象。VB.NET编程语言中的AddHandler语句的补充是RemoveHandler语句。RemoveHandler需要的参数与AddHandler的相同,它的效果相反。它通过事件源调用remove_LargeWithdraw方法从已注册的处理方法列表中删除目标处理方法。
Dim account1 As New BankAccount()
'注册事件处理程序
AddHandler account1.LargeWithdraw, AddressOf AccountHandlers.LogWithdraw
'删除事件处理程序注册
RemoveHandler account1.LargeWithdraw, AddressOf AccountHandlers.LogWithdraw
- 1.
- 2.
- 3.
- 4.
- 5.
你已经看到了实现使用事件的回调设计需要的所有步骤了。代码显示了一个完整的应用程序,在该程序中已经注册了两个事件处理程序从BankAccount对象的LargeWithdraw事件接收回调通知。
Delegate Sub LargeWithdrawHandler(ByVal Amount As Decimal)
Class BankAccount
Public Event LargeWithdraw As LargeWithdrawHandler
Sub Withdraw(ByVal Amount As Decimal)
'如果需要的话就发送通知
If (Amount > 5000) Then
RaiseEvent LargeWithdraw(Amount)
End If
'执行撤消
End Sub
End Class
Class AccountHandlers
Shared Sub LogWithdraw(ByVal Amount As Decimal)
'把撤消信息写入日志文件
End Sub
Shared Sub GetApproval(ByVal Amount As Decimal)
'阻塞直到管理者批准
End Sub
End Class
Module MyApp
Sub Main()
'建立银行帐号对象
Dim account1 As New BankAccount()
'注册事件处理程序
AddHandler account1.LargeWithdraw, _
AddressOf AccountHandlers.LogWithdraw
AddHandler account1.LargeWithdraw, _
AddressOf AccountHandlers.GetApproval
'做一些触发回调的事情
account1.Withdraw(5001)
End Sub
End Module
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
结论
尽管使用事件的动机和一些语法与早期版本的VB.NET编程相比仍然没有改变,但是你不得不承认情况有很大不同了。你能看到,你对如何响应事件的控制力比以前大多了。如果你将使用委托编程,这就很实际了。
【编辑推荐】