2

我正在使用 VB.Net 4 并成功使用具有以下签名的类:

Sub Register(Of TMessage)(recipient As Object, action As System.Action(Of TMessage))

我想了解 VB 中的 lambda,所以我想看看是否可以简化我当前的代码。

当前:我在类的构造函数中有以下内容(为清楚起见进行了简化)

Public Sub New()
    Dim myAction As New Action(Of String)(AddressOf HandleMessage)
    Messenger.Default.Register(Of [String])(Me, myAction)            
End Sub

后来在课堂上我有以下内容:

Private Function HandleMessage(sMsg As String)
    If sMsg = "String Value" Then
        If Me._Selection.HasChanges Or Me._Selection.HasErrors Then
            Return True
        End If
        Return False
    Else
        Return False
    End If
End Function

问题:有没有办法将它简化为像 C# 中的 lambda,我不必在构造函数中声明 MyAction 变量,而只需将字符串值传递给带有寄存器子的HandleMessage 函数“ inline ”?(我希望这是有道理的)

4

1 回答 1

3

So your constructor code is equivalent to:

Messenger.[Default].Register(Of String)(Me,
    Function(sMsg)
        If sMsg = "String Value" Then
            If Me._Selection.HasChanges Or Me._Selection.HasErrors Then
                Return True
            End If
            Return False
        Else
            Return False
        End If
    End Function)

It's worth mentioning though you don't need to use lambdas just to get rid of your explicit delegate creation. This is perfectly legal too:

Messenger.[Default].Register(Of String)(Me, AddressOf HandleMessage)

There is a bit of strangeness though with your example: you've declared your Register method as taking an Action(Of TMessage) which means the function passed needs no return value. Your function however is returning a Boolean. Visual Basic here is doing the fancy "delegate relaxation" and is throwing away the return value. So all your Return True/Return False bits aren't actually doing anything special.

于 2013-01-25T07:01:40.263 回答