委托

原文链接:http://www.cnblogs.com/hzb2001/archive/2011/06/29/2093835.html

Public Class Form1

    '定义委托
    Private Delegate Sub MyMsg(ByVal str As String)

 

    '实现委托,方法签名与前面定义的委托相同
    Private Sub showmsg(ByVal str As String)
        MessageBox.Show(str & " from showmsg")
    End Sub

 

    '实现另一个委托,,方法签名与前面定义的委托相同
    Private Sub shownamemsg(ByVal str As String)
        MessageBox.Show(str & ",Phoenix" & " from shownamemsg")
    End Sub

 

   '使用委托, 把调用哪个方法的权利下放到执行代码那里
    Private Sub showinfo(ByVal dd As MyMsg, ByVal str As String)
        dd(str)
        '在vb中支持调用invoke
        'dd.Invoke(str)
    End Sub

 

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        '采用了简写形式. 完整形式应该是
        'showinfo(New MyMsg(AddressOf showmsg), "Hello")
        showinfo(AddressOf showmsg, "Hello")

   

     '采用了简写形式.完整形式应该是
        'showinfo(New MyMsg(AddressOf shownamemsg), "Hello")
        showinfo(AddressOf shownamemsg, "Hello")

 

       '委托链表. 依次调用委托链上的每个方法. 注意此处不能采用简写形式
        '以下为错误写法
        'showinfo([Delegate].Combine(AddressOf showmsg, AddressOf shownamemsg), "Hello")
        showinfo([Delegate].Combine(New MyMsg(AddressOf showmsg), New MyMsg(AddressOf shownamemsg)), "Hello")

   

     '用lambda函数代替委托
        showinfo(Sub(str) MessageBox.Show(str & " from lambda"), "Hello")

    End Sub


End Class

转载于:https://www.cnblogs.com/hzb2001/archive/2011/06/29/2093835.html

上一篇:Python档案袋(生成器、迭代器、队列 )


下一篇:搜狗输入法的右下角弹窗“天猫618狂欢红包”的不显示方法