在变量中传递和存储可选委托

Pass and store optional delegate in variable

我试图在实例化时将可选的回调参数传递给 class。我需要一个回调方法来格式化一些可能需要也可能不需要格式化的值。

这是我尝试做的简化代码:

Public Class ColumnSpec
    Property Title As String
    Property Name As String
    Property Value As String

    Delegate Function CallBack(aValue As String) As String
    Property HasCallBack As Boolean

    Public Sub New(aTitle As String, aName As String, Optional aCallBack As CallBack = Nothing)
        _Title = aTitle
        _Name = aName
        ' How do I assign aCallBack to the delegate function here?
        _HasCallBack = aCallBack IsNot Nothing
    End Sub
End Class

我在实例化 ColumnSpec 时可能会也可能不会传递回调函数。

在另一个class中,我需要检查并调用委托。

Public Class MyClass

   Public Function FormatText(Value as String) As String
       Return Value + "01234"  ' Return value after modifying
   End Function

   Public Function RenderValue() As String
       Dim lNewCol1 as ColumnSpec("Title1", "Name2", AddressOf FormatText)
       Dim lNewCol2 as ColumnSpec("Title2", "Name2")

       ' How do I check if there is a delegate and call it?
       If lNewCol1.HasCallBack Then lNewCol1.Value =  lNewCol1.CallBack(lNewCol1.HasCallBack)
       If lNewCol2.HasCallBack Then lNewCol2.Value =  lNewCol1.CallBack(lNewCol2.HasCallBack)
   End Function
End Class

我对代表完全陌生。关于如何解决这个问题的任何想法?

你的行Delegate Function CallBack(aValue As String) As String只声明了回调的类型。您需要一个单独的 属性 或字段来保存引用。

因此,您可以稍微修改 class:

Delegate Function CallbackFunction(aValue As String) As String

Public ReadOnly Property Callback As CallbackFunction

Public ReadOnly Property HasCallback As Boolean
    Get
        'Alternatively, you could assign the value in the ctor as in your code...
        Return Callback IsNot Nothing
    End Get
End Property

Public Sub New(Optional aCallback As CallbackFunction = Nothing)
    Me.Callback = aCallback
End Sub

您的客户端代码没有问题as-is,不需要更改。

如果您不关心回调函数的命名类型,您也可以使用更新的语法,例如

Public ReadOnly Property Callback As Func(Of String, String)

同时相应地修改构造函数。

经过此修改,客户端代码仍然可以正常工作 as-is。

Action 之于 Sub 如同 Func 之于 Function。)