VB.NET委托的使用

委托三个步骤 

 1、声明委托   用Delegate 声明一个委托 类型  参数要和 被委托的方法一样  例如  Delegate Function a(byval x as string)  as string 

2、实例化委托     dim  t as new a(AddressOf      Function Name)

3.通过 t(参数)   或者  t.Invoke(参数调用委托)

 

 

 

Module module1
    Delegate Function a(ByVal x As Integer, ByVal y As Integer) As Integer    '声明委托类型 委托可以使一个对象调用另一个对象的方法
    Function sum(ByVal x As Integer, ByVal y As Integer) As Integer
        Return (x + y)
    End Function
    Sub main()
        Dim d As New a(AddressOf sum)  '实例化委托
        Dim s = 0
        s = d.Invoke(1, 2)    '执行委托
        Console.WriteLine(s.ToString())
        s = d(1, 2)    '执行委托
        Console.WriteLine(s.ToString())

        MsgBox("")

    End Sub
End Module

 

 

 

 

在UI编程中  比如说我们想用一个函数 处理 多个控件的单击事件 只需要在那个事件响应方法的后面加上 例如

handles button1.click   ,  button2.click  .....来实现

posted @ 2011-11-01 18:07  programmer小卫  阅读(1821)  评论(0编辑  收藏  举报