示例:创建一个通用的排序方法!
1. 声明委托
public Delegate Function Compare(v1 as object,v2 as object) as boolean
这里将方法签名定义为一个数据类型。这个新的数据类型被命名为Compare。可以在代码中使用该数据类型来声明方法所接受的变量或参数。用这个数据类型声明的变量和参数可以保存与已定义方法签名相匹配的方法的地址,然后可以通过使用该变量来调用方法。
任何使用了下面签名的方法都可以被视为Compare数据类型。
f(object,object)
2. 使用委托数据类型
编写一个将委托数据类型作为参数的过程,就是说无论谁调用这个过程,都必须传递符合该接口的方法的地址。
pub 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 outer+1 to UBound(theData)
if greaterThan.Invoke(theData(outer),theData(inner)) then
temp=theData(outer)
theData(outer)=theData(inner)
theData(inner)=temp
next
next
end sub
greaterThan 参数是用来保存Compare委托所定义的方法签名相匹配的方法地址的变量。任何带有匹配签名的方法地址都以作为一个参数传递到DoSort方法里面来。
Invoke方法是从代码中调用委托的方法。
3. 实现委托方法
接下来就需要来实现一个被委托的方法了。
public function PersonCompare(person1 as object,person2 as object)as boolean
if person1.age>person2.age then return true else return false
end function
这个函数的签名(object,Object)要与Compare定义的方法签名完全匹配,函数的值也必须是Boolean。函数的名称是什么不重要,重要的参数的数量、顺序、类型以及函数的返回值类型要一致。
调用示例:
Public class person
property Name as string
property age as integer
end class
……
dim persons(4) as person
persons(0)=new person with{.name="AAA",.age=12}
persons(1)=new person with{.name="BBB",.age=56}
persons(2)=new person with{.name="CCC",.age=18}
persons(3)=new person with{.name="DDD",.age=31}
persons(4)=new person with{.name="EEE",.age=12}
DoSort(persons,addressOf PersonCompare)
委托就是把函数作为一个参数,在自己内部运行调用外部函数的机制。