委托作为VB.NET中的参数
时间:2020-03-06 14:33:57 来源:igfitidea点击:
背景故事:我正在使用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一样容易吗?我想可以做的还不止于此(请原谅我对这个主题的无知-代表确实是我想了解的更多东西,但到目前为止,他们还不了解我的知识)。
解决方案
我们可以在VB.NET(和C#)中将委托作为参数传递。请看这里的例子。
Public Delegate errorCall(ByVal error As String, Params objs As Objects()) CheckDifference(10, 0, AddressOf log.ErrorFormat)
请原谅格式:P
不过,基本上,使用正确的签名创建所需的委托,并将其地址传递给方法。
我们首先要在类/模块级别声明一个委托(所有这些代码均来自内存/未经测试):
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 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)