快捷簡單的VB.NET編程事件方法介紹
看一個關于VB.NET編程的例子,在這里呢我使用另一種方法來說明當你建立和注冊一個事件處理程序時到底發(fā)生了什么事情。一旦你明白事情是怎么回事,你也許會感激使用了更簡潔的語法實現(xiàn)了相同的目標,一起來看看吧:
- '建立銀行帳號對象
- Dim account1 As New BankAccount()
- '注冊事件處理程序
- AddHandler account1.LargeWithdraw, AddressOf AccountHandlers.LogWithdraw
- AddHandler account1.LargeWithdraw, AddressOf AccountHandlers.GetApproval
因為AddHandler語句期待一個委托對象作為第二個參數(shù),你能使用速記語法--AddressOf操作符后緊跟目標處理方法的名字。當Visual Basic .NET編譯器看到該語法時,它接著產生額外的代碼來建立作為事件處理程序服務的委托對象。VB.NET編程語言中的AddHandler語句的補充是RemoveHandler語句。RemoveHandler需要的參數(shù)與AddHandler的相同,它的效果相反。它通過事件源調用remove_LargeWithdraw方法從已注冊的處理方法列表中刪除目標處理方法。
- Dim account1 As New BankAccount()
- '注冊事件處理程序
- AddHandler account1.LargeWithdraw, AddressOf AccountHandlers.LogWithdraw
- '刪除事件處理程序注冊
- RemoveHandler account1.LargeWithdraw, AddressOf AccountHandlers.LogWithdraw
你已經看到了實現(xiàn)使用事件的回調設計需要的所有步驟了。代碼顯示了一個完整的應用程序,在該程序中已經注冊了兩個事件處理程序從BankAccount對象的LargeWithdraw事件接收回調通知。
- Delegate Sub LargeWithdrawHandler(ByVal Amount As Decimal)
- Class BankAccount
- Public Event LargeWithdraw As LargeWithdrawHandler
- Sub Withdraw(ByVal Amount As Decimal)
- '如果需要的話就發(fā)送通知
- If (Amount > 5000) Then
- RaiseEvent LargeWithdraw(Amount)
- End If
- '執(zhí)行撤消
- 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
- '做一些觸發(fā)回調的事情
- account1.Withdraw(5001)
- End Sub
- End Module
結論
盡管使用事件的動機和一些語法與早期版本的VB.NET編程相比仍然沒有改變,但是你不得不承認情況有很大不同了。你能看到,你對如何響應事件的控制力比以前大多了。如果你將使用委托編程,這就很實際了。
【編輯推薦】