【问题标题】:Pass a delegate in parameter在参数中传递委托
【发布时间】:2012-07-23 23:53:26
【问题描述】:

我有

Function Bar(s As String) ...

我需要创建一个函数

Me.Foo(myInt, AddressOf Bar)

Foo的签名应该怎么写?

【问题讨论】:

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


    【解决方案1】:

    使用泛型 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
    

    【讨论】:

      【解决方案2】:

      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
      

      在您的代码中的某处调用您的测试函数:

      CheckDifference(Foo, Bar, AddressOf log.WriteWarn)
      

      或者

      CheckDifference(Foo, Bar, AddressOf log.WriteError)
      

      【讨论】:

      • 我真的应该为每个这样的函数调用之王声明一个公共代表,即使我不使用它们吗?
      猜你喜欢
      • 1970-01-01
      • 2013-11-17
      • 2012-07-12
      • 1970-01-01
      • 2011-05-29
      • 2015-07-07
      • 2015-08-11
      • 2015-03-06
      • 2016-09-03
      相关资源
      最近更新 更多