委托就是将一段程序作为参数传递到方法中。委托概念格式化了声明要调用的例程以及调用此例程的过程。
对于回调方法,.NET环境使用的底层机制就是委托.Visual Basic在实现Event、RaiseEvent、WithEvcnts和Handles关键字时,就在后台使用委托.
- 首先声明—个委托,它定义了一个方法的签名。该方法比较两个对象的值,并返同一个布尔值,指出第一个对象的值是否大于第二个对象。
Public Delegate Function Comprare(ByVal v1 As Object, ByVal v2 As Object) As Boolean
- 然后创建一个排序算法,使用这个通用比较方法对数据排序。
Public Sub DoSort(ByVal theData() As Object, ByVal greaterThan As Compare)
Dim outer As Integer
Dim inner As Integer
Dim temp As Object
For outer = 0 To UBound(theData)
For inner = outer + 1 To UBound(theData)
If greaterThan.Invoke(theData(outer), theData(inner)) Then
temp = theData(outer)
theData(outer) = theData(inner)
theData