VB.NET中怎么实现编程事件

VB.NET中怎么实现编程事件,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

十余年品牌的成都网站建设公司,1000多家企业网站设计经验.价格合理,可准确把握网页设计诉求.提供定制网站建设、商城网站开发、成都微信小程序、响应式网站开发等服务,我们设计的作品屡获殊荣,是您值得信赖的专业网络公司。

看一个关于VB.NET编程的例子,在这里呢我使用另一种方法来说明当你建立和注册一个事件处理程序时到底发生了什么事情。一旦你明白事情是怎么回事,你也许会感激使用了更简洁的语法实现了相同的目标,一起来看看吧:

'建立银行帐号对象  Dim account1 As New BankAccount()  '注册事件处理程序  AddHandler account1.LargeWithdraw, AddressOf AccountHandlers.LogWithdraw  AddHandler account1.LargeWithdraw, AddressOf AccountHandlers.GetApproval

因为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

你已经看到了实现使用事件的回调设计需要的所有步骤了。代码显示了一个完整的应用程序,在该程序中已经注册了两个事件处理程序从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

关于VB.NET中怎么实现编程事件问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。


网页名称:VB.NET中怎么实现编程事件
浏览路径:http://pwwzsj.com/article/jpoedg.html