Does VB.NET have anonymous functions?

前端 未结 6 1521
陌清茗
陌清茗 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条回答
  • Visual Basic .NET has only lambda expressions.

    It does not support 'anonymous delegates" in the current version, though it will (and on multiple lines at that) in VS2010.

    Right now the only option is to declare your method somewhere and pass it with the Addressof operator.

    0 讨论(0)
  • 2020-12-15 23:17

    in this example I have a list of operations but only want to find one from a list (of T) where the IDs match:

    Return operations.Find(Function(p) p.OperationID = operationID)
    

    operationID is a local variable passed in to the method and operations is a generic list.

    0 讨论(0)
  • 2020-12-15 23:27

    This is inaccurate. VB.NET does in fact have anonymous methods. Here is an example:

    Private Function JsonToObject(Of T)(Value As String) As T
        Dim JavaScriptSerializer As New System.Web.Script.Serialization.JavaScriptSerializer()
        Return JavaScriptSerializer.Deserialize(Of T)(Value)
    End Function
    
    Dim People As Generic.List(Of Person) = JsonToObject(Of Generic.List(Of Person))(Json)
    
    0 讨论(0)
  • 2020-12-15 23:28

    VB9 has only single-line anonymous functions. We're adding full statement and multi-line lambdas in VB10.

    0 讨论(0)
  • 2020-12-15 23:29

    Anonymous isn't a delegate or function it's a strong dynamical type

    you can use generic functions

    Sub Main()
          Dim PersonDynamicType = AnonyFunc(New With {.Name = "david", .Family = "Fisher"})
          Console.Write(PersonDynamicType.Name)
    End Sub
    
    Function AnonyFunc(Of t)(v As t) As t
          Return v
    End Function
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题