背景故事:我正在使用 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作为委托?

我在VS 2008和.NET 3.5 SP1中使用VB.NET。此外,我对一般的代表来说还是比较新的,所以如果这个问题措辞不同以消除任何含糊之处,请告诉我。

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

有帮助吗?

解决方案

声明你的代表签名:

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)

其他提示

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

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)
Public Delegate errorCall(ByVal error As String, Params objs As Objects())
CheckDifference(10, 0, AddressOf log.ErrorFormat)

请原谅格式:P

但基本上,使用正确的签名创建所需的委托,并将其地址传递给方法。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top