VB.NET中将委托作为参数

9

背景:我正在使用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#)中将委托作为参数传递。点击这里查看一个示例。 - alex
3个回答

15

声明委托签名:

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)

1

首先,您需要在类/模块级别声明一个委托(所有这些代码都是从记忆中而非经过测试的):

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)

0
Public Delegate errorCall(ByVal error As String, Params objs As Objects())
CheckDifference(10, 0, AddressOf log.ErrorFormat)

请原谅格式:P
基本上,创建您想要的委托,具有正确的签名,并将其地址传递给该方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接