1
我很困惑在引發事件實例和使用委託作爲函數指針:與活動困惑
我與低於該分揀整數陣列,而不改變創建一個通用排序功能此功能指針示例程序明確主排序功能。
' Returns True if need to swap
Delegate Function CompareFunc(ByVal x As Integer, ByVal y As Integer) As Boolean
' Here are two alternative target methods for the delegate—one for an ascending sort and one for a
' descending sort:
Function SortAscending(ByVal x As Integer, ByVal y As Integer) As Boolean
If y < x Then
SortAscending = True
End If
End Function
Function SortDescending(ByVal x As Integer, ByVal y As Integer) As Boolean
If y > x Then
SortDescending = True
End If
End Function
' Now we can define the sort routine. Note the call to the Invoke method of the delegate:
Sub BubbleSort(ByVal CompareMethod As CompareFunc, ByVal IntArray() As Integer)
Dim i, j, temp As Integer
For i = 0 To Ubound(IntArray)
For j = i + 1 To Ubound(IntArray)
If CompareMethod.Invoke(IntArray(i), IntArray(j)) Then
Temp = IntArray(j)
IntArray(j) = IntArray(i)
IntArray(i) = Temp
End If
Next j
Next i
End Sub
' Here is some code to exercise this example:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim i As Integer
Dim iArray() As Integer = New Integer() {6, 2, 4, 9}
' The code below tells us that we have created a generic sort function thus eliminating the need of having multiple sort function to do different sorts.
BubbleSort(AddressOf SortAscending, iArray)
For i = 0 To 3
Debug.WriteLine(CStr(iArray(i)))
Next
Debug.WriteLine
BubbleSort(AddressOf SortDescending, iArray)
For i = 0 To 3
Debug.WriteLine(CStr(iArray(i)))
Next
End Sub
那麼這個例子的RaiseEvent走過這混淆了我,那是假設是?:
Module Module1
Dim WithEvents ValueInfo As New Value()
Class Value
Public Event ValueUp(ByVal Amount As Double)
Public Event ValueDown(ByVal Amount As Double)
Public Event Result(ByVal Amount As Double, ByVal AnnounceDate As DateTime)
Public Sub GenerateEvents()
RaiseEvent ValueUp(2)
RaiseEvent ValueDown(-5.5)
RaiseEvent Result(1.25, Now())
End Sub
End Class
Sub PriceGoingUp(ByVal Price As Double)
Console.WriteLine("Up: " & Price)
End Sub
Sub PriceGoingDown(ByVal Price As Double)
Console.WriteLine("Down: " & Price)
End Sub
Sub ResultAnnouncement(ByVal Amount As Double, ByVal AnnounceDate As DateTime)
Console.WriteLine("Result: " & Amount & " " & AnnounceDate)
End Sub
Sub Main()
AddHandler ValueInfo.ValueUp, AddressOf PriceGoingUp
AddHandler ValueInfo.ValueDown, AddressOf PriceGoingDown
AddHandler ValueInfo.Result, AddressOf ResultAnnouncement
ValueInfo.GenerateEvents()
End Sub
End Module
上面的例子中替代我將不勝感激,如果有人可以提供解釋。謝謝!