vbnet引用事件的简单介绍

vb.net中如何用事件和委托,会C#中的事件和委托,但不知VB.net中的语法 , 望给个简单的例子熟悉语法 。一委托vbnet引用事件:此示例演示如何将方法与委托关联然后通过委托调用该方法 。
创建委托和匹配过程
创建一个名为 MySubDelegate 的委托 。
Delegate Sub MySubDelegate(ByVal x As Integer)
声明一个类vbnet引用事件,该类包含与该委托具有相同签名的方法 。
Class class1
Sub Sub1(ByVal x As Integer)
MsgBox("The value of x is: "CStr(x))
End Sub
【vbnet引用事件的简单介绍】End Class
定义一个方法,该方法创建该委托的实例并通过调用内置的 Invoke 方法调用与该委托关联的方法 。
Protected Sub DelegateTest()
Dim c1 As New class1
' Create an instance of the delegate.
Dim msd As MySubDelegate = AddressOf c1.Sub1
' Call the method.
msd.Invoke(10)
End Sub
二、事件
下面的示例程序阐释如何在一个类中引发一个事件 , 然后在另一个类中处理该事件 。AlarmClock 类定义公共事件 Alarm , 并提供引发该事件的方法 。AlarmEventArgs 类派生自 EventArgs,并定义 Alarm 事件特定的数据 。WakeMeUp 类定义处理 Alarm 事件的 AlarmRang 方法 。AlarmDriver 类一起使用类,将使用 WakeMeUp 的 AlarmRang 方法设置为处理 AlarmClock 的 Alarm 事件 。
该示例程序使用事件和委托和引发事件中详细说明的概念 。
示例
' EventSample.vb.
'
Option Explicit
Option Strict
Imports System
Imports System.ComponentModel
Imports Microsoft.VisualBasic
Namespace EventSample
' Class that contains the data for
' the alarm event. Derives from System.EventArgs.
'
Public Class AlarmEventArgs
Inherits EventArgs
Private _snoozePressed As Boolean
Private nrings As Integer
'Constructor.
'
Public Sub New(snoozePressed As Boolean, nrings As Integer)
Me._snoozePressed = snoozePressed
Me.nrings = nrings
End Sub
' The NumRings property returns the number of rings
' that the alarm clock has sounded when the alarm event
' is generated.
'
Public ReadOnly Property NumRings() As Integer
Get
Return nrings
End Get
End Property
' The SnoozePressed property indicates whether the snooze
' button is pressed on the alarm when the alarm event is generated.
'
Public ReadOnly Property SnoozePressed() As Boolean
Get
Return _snoozePressed
End Get
End Property
' The AlarmText property that contains the wake-up message.
'
Public ReadOnly Property AlarmText() As String
Get
If _snoozePressed Then
Return "Wake Up!!! Snooze time is over."
Else
Return "Wake Up!"
End If
End Get
End Property
End Class
' Delegate declaration.
'
Public Delegate Sub AlarmEventHandler(sender As Object, _
e As AlarmEventArgs)
' The Alarm class that raises the alarm event.
'
Public Class AlarmClock
Private _snoozePressed As Boolean = False
Private nrings As Integer = 0
Private stopFlag As Boolean = False
' The Stop property indicates whether the
' alarm should be turned off.
'
Public Property [Stop]() As Boolean
Get
Return stopFlag
End Get
Set
stopFlag = value
End Set
End Property
' The SnoozePressed property indicates whether the snooze
' button is pressed on the alarm when the alarm event is generated.
'
Public Property SnoozePressed() As Boolean
Get
Return _snoozePressed
End Get
Set
_snoozePressed = value
End Set
End Property

推荐阅读