在参数中传递委托

时间:2012-07-23 15:40:36

标签: .net vb.net .net-4.0

我有

Function Bar(s As String) ...

我需要创建一个函数

Me.Foo(myInt, AddressOf Bar)

我该怎么写Foo的签名?

2 个答案:

答案 0 :(得分:2)

使用通用Func(Of Type)关键字可能是最简单的。

Public Function Foo(i As Integer, f As Func(Of String, Integer)) As String
    Dim i2 = f.Invoke("test")
    Return "42"
End Function

答案 1 :(得分:1)

This may help you

声明你的代表签名:

Public Delegate Sub Format(ByVal value As String)

定义您的测试功能:

Public Sub CheckDifference(ByVal A As Integer, _
                           ByVal B As Integer, _
                           ByVal format As Format)
    If (B - A) > 5 Then
        format.Invoke(String.Format( _
        "Difference ({0}) is outside of acceptable range.", (B - A)))
    End If
End Sub

代码中的某处调用Test函数:

CheckDifference(Foo, Bar, AddressOf log.WriteWarn)

或者

CheckDifference(Foo, Bar, AddressOf log.WriteError)