委托是面向对象函数指针的一种形式,它允许通过对函数进行引用的方法来间接地调用该函数。委托可用于与事件处理程序挂接,以及将过程从一个过程传递到另一个过程。
vb.net 委托的声明方式如下:
各个参数的具体解释,请查阅msdn.
1. 函数委托:
[ <attrlist> ] [ accessmodifier ] _
[ Shadows ] Delegate Function name [( Of typeparamlist )] [([ parameterlist ])] [ As type ]
example:
delegate function add(byval x as integer,byval y as integer) as integer
2.过程委托:
[ <attrlist> ] [ accessmodifier ] _
[ Shadows ] Delegate Sub name [( Of typeparamlist )] [([ parameterlist ])] [ As type ]
example:
delegate sub add_sub(byval x as integer,byval y as integer) as integer
定义一个委托实例:
addressof [sub_name|function_name]
sub_name的参数列表一定要和委托的参数列表完全匹配
function_name的参数列表以及返回值类型一定要和委托的参数列表、返回值类型完全匹配
最后通过委托的invoke方法来实现调用与之关联的方法或过程
下面是代码实例:
//定义一个包含过程和方法的类
class class1
public function add_function(byval x as integer,byval y as integer) as integer
return x+y
end function
pubic sub add_sub(byval x as integer,byval y as integer)
msgBox(ctype(x+y).tostring)
end sub
end class
class delegate_test
delegate function add_f(byval x as integer,byval y as integer) as integer
deletgate sub add_s (byval x as integer,byval y as ineger)
sub test()
dim c as class1
dim a_f as add_f
dim a_s as add_s
dim r as integer
c=new class1
end sub
end class