【问题标题】:Delegates as parameters in VB.NETVB.NET 中作为参数的委托
【发布时间】:2008-09-22 21:01:11
【问题描述】:

背景故事:我正在使用log4net 来处理我正在进行的项目的所有日志记录。可以在几种不同的情况下调用一种特定的方法——一些保证日志消息是错误的,而另一些保证日志消息是警告的。

那么,举个例子,我怎么转

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

进入更多类似的内容:

Public Sub CheckDifference(ByVal A As Integer, ByVal B As Integer, "Some delegate info here")
  If (B - A) > 5 Then
    **delegateinfo**.Invoke("Difference ({0}) is outside of acceptable range.", (B - A))
  End If
End Sub

这样我就可以调用它并将 log.ErrorFormat 或 log.WarnFormat 作为委托传递?

我将 VB.NET 与 VS 2008 和 .NET 3.5 SP1 一起使用。另外,我对代表们一般来说还很陌生,所以如果这个问题应该用不同的措辞来消除任何歧义,请告诉我。

编辑:另外,我如何在类构造函数中将委托初始化为 ErrorFormat 或 WarnFormat?会像myDelegate = log.ErrorFormat 一样简单吗?我想还有更多的东西(请原谅我对这个主题的无知——代表确实是我想了解更多的东西,但到目前为止他们还没有让我理解)。

【问题讨论】:

  • 您可以在 VB.NET(和 C#)中将委托作为参数传递。以here 为例。

标签: vb.net delegates lambda log4net


【解决方案1】:

声明您的代表签名:

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)

【讨论】:

    【解决方案2】:

    您首先要在类/模块级别声明一个委托(所有这些代码都来自内存/未经测试):

    Private Delegate Sub LogErrorDelegate(txt as string, byval paramarray fields() as string)
    

    然后..您需要将其声明为您的类的属性,例如

    Private _LogError
    Public Property LogError as LogErrorDelegate
      Get 
        Return _LogError
      End Get
      Set(value as LogErrorDelegate)
        _LogError = value
      End Set
    End Property
    

    实例化委托的方式是:

    Dim led as New LogErrorDelegate(AddressOf log.ErrorFormat)
    

    【讨论】:

      【解决方案3】:
      Public Delegate errorCall(ByVal error As String, Params objs As Objects())
      CheckDifference(10, 0, AddressOf log.ErrorFormat)
      

      请原谅格式:P

      不过,基本上,使用正确的签名创建您想要的委托,并将其地址传递给方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-17
        • 1970-01-01
        • 2015-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多