VB委托和事件
2011-01-25 10:26:28| 分类: VB | 标签: |举报 |字号大中小 订阅
比如下边引用的这个例子
当小偷偷东西时,警察会罚钱,自愿反扒手会把小偷打一顿
在这里
小偷偷东西是一个事件
警察会罚钱,自愿反扒手会把小偷打一顿,是该事件所引起的,所触发的东西
小偷,警察,自愿反扒手都是一个对象
Module Module1
Delegate Sub PlayGameHandler(ByVal sender As Object, ByVal e As System.EventArgs)
Public WithEvents w As wl
Sub Main()
Console.WriteLine("新的一天开始了....")
Dim p As New jc
w = New wl
Dim pp As New zyfpd
AddHandler w.PlayGame, AddressOf p.KouQian
'如果小偷偷东西则引用自愿反扒队的打人处理程序
AddHandler w.PlayGame, AddressOf pp.DaRen
w.TouDongXi()
Console.WriteLine("天黑了....")
Console.ReadLine()
End Sub
Public Class jc
Sub New()
Console.WriteLine("生成警察。。。。")
End Sub
Public Sub KouQian(ByVal sender As Object, ByVal e As System.EventArgs)
Console.WriteLine("警察:好小子,胆敢偷东西。。。。")
System.Threading.Thread.Sleep(3000)
Console.WriteLine("警察:看看你小子有多少钱。。。")
Dim f As wl = sender
System.Threading.Thread.Sleep(3000)
Console.WriteLine("无赖 的钱: " + f.Qian.ToString)
System.Threading.Thread.Sleep(3000)
Console.WriteLine("开始扣钱......")
System.Threading.Thread.Sleep(3000)
f.Qian = f.Qian - 500
Console.WriteLine("扣完了....现在无赖 还剩下:" + f.Qian.ToString())
System.Threading.Thread.Sleep(3000)
End Sub
End Class
Public Class wl
Public Event PlayGame As PlayGameHandler
Private m_Money As Integer
Private ey As Integer
Sub New()
Console.WriteLine("生成无赖....")
m_Money = 1000
ey = 5
End Sub
Property AiDa() As Integer
Get
Return ey
End Get
Set(ByVal value As Integer)
ey = value
End Set
End Property
Property Qian() As Integer
Get
Return m_Money
End Get
Set(ByVal value As Integer)
m_Money = value
End Set
End Property
Public Sub TouDongXi()
Console.WriteLine("无赖开始偷东西了")
System.Threading.Thread.Sleep(3000)
'实例化事件参数
Dim e As New System.EventArgs
RaiseEvent PlayGame(Me, e)
End Sub
End Class
Public Class zyfpd
Sub New()
Console.WriteLine("自愿反扒队来了.....")
System.Threading.Thread.Sleep(3000)
End Sub
Public Sub DaRen(ByVal sender As Object, ByVal e As System.EventArgs)
System.Threading.Thread.Sleep(3000)
Console.WriteLine("自愿反扒队:好小子,敢偷东西...")
System.Threading.Thread.Sleep(3000)
Console.WriteLine("自愿反扒队:你小子挨过几次打了...")
Dim bn As wl = sender
System.Threading.Thread.Sleep(3000)
Console.WriteLine("无赖:" + bn.AiDa.ToString + "次")
System.Threading.Thread.Sleep(3000)
Console.WriteLine("自愿反扒队:那也得揍你,先来一拳.... ")
System.Threading.Thread.Sleep(3000)
Console.WriteLine("自愿反扒队:再来一脚......")
System.Threading.Thread.Sleep(3000)
Console.WriteLine("自愿反扒队:打完了...赶紧去医院吧...")
End Sub
End Class
End Module