Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
VB.NET中作为参数的委托_Vb.net_Delegates_Lambda_Log4net - Fatal编程技术网

VB.NET中作为参数的委托

VB.NET中作为参数的委托,vb.net,delegates,lambda,log4net,Vb.net,Delegates,Lambda,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.

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

那么,作为一个例子,我怎样才能

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与VS2008和.NET3.5SP1一起使用。另外,我对代表们一般来说都是新手,所以如果这个问题的措辞应该有所不同,以消除任何歧义,请让我知道

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

请原谅格式错误:p


但基本上,创建您想要的具有正确签名的委托,并将其地址传递给方法。

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

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

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
CheckDifference(Foo, Bar, AddressOf log.WriteWarn)
在代码中的某个地方调用测试函数:

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)


您可以在VB.NET(和C#)中将委托作为参数传递。请看一个例子。
CheckDifference(Foo, Bar, AddressOf log.WriteError)