背景:我正在使用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作为委托传递。
我在VS2008和.NET 3.5 SP1上使用VB.NET。此外,一般来说,我对代表是相当陌生的,所以如果这个问题应该用不同的措辞来消除任何歧义,请让我知道。
编辑:另外,我如何在类构造函数中将委托初始化为ErrorFormat或WarnFormat?它会像myDelegate = log.ErrorFormat一样简单吗?我想还有更多的原因(请原谅我对这个问题的无知--我真的想了解更多关于委托的知识,但到目前为止,我还不能理解它们)。
发布于 2008-09-22 21:11:10
声明您的委派签名:
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)发布于 2008-09-22 21:05:59
您首先需要在类/模块级别声明一个委托(所有这些代码都来自内存/未经过测试):
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)发布于 2008-09-22 21:04:48
Public Delegate errorCall(ByVal error As String, Params objs As Objects())
CheckDifference(10, 0, AddressOf log.ErrorFormat)请原谅格式错误:P
基本上,使用正确的签名创建所需的委托,并将其地址传递给该方法。
https://stackoverflow.com/questions/117623
复制相似问题