Does VB.NET have anonymous functions?

前端 未结 6 1519
陌清茗
陌清茗 2020-12-15 22:42

From what I can find on google, VB.NET only has one-statement lambdas, and not multi-statement anonymous functions. However, all the articles I read were talking about old v

6条回答
  •  有刺的猬
    2020-12-15 23:35

    It does in VB10:

    Dim food = New With {
        .ID = 1,
        .Name = "Carrot",
        .Type = (
            Function(name As String)
                If String.IsNullOrEmpty(name) Then Return String.Empty
    
                Select Case name.ToLower()
                    Case "apple", "tomato": Return "Fruit"
                    Case "potato": Return "Vegetable"
                End Select
    
                Return "Meat"
            End Function
        )(.Name)
    }
    Dim type = food.Type
    

    Or, corresponding to your code:

    Sub HandleErrors(codeBlock As Action)
        Try
            codeBlock()
        Catch e As Exception
            ' log exception, etc.
        End Try
    End Sub
    
    HandleErrors(Sub()
            Dim x = foo()
            x.DoStuff()
            ' etc.
        End Sub)
    

提交回复
热议问题