MST
星途 面试题库

面试题:Visual Basic中匿名方法与Lambda表达式的基础应用

请用Visual Basic分别使用匿名方法和Lambda表达式实现一个简单的委托,该委托接收两个整数参数并返回它们的和。
37.9万 热度难度
编程语言Visual Basic

知识考点

AI 面试

面试题答案

一键面试

使用匿名方法

Module Module1
    Delegate Function AddDelegate(ByVal a As Integer, ByVal b As Integer) As Integer
    Sub Main()
        Dim add As AddDelegate = AddressOf AddNumbers
        Dim result1 As Integer = add(3, 5)
        Console.WriteLine("使用命名方法的结果: " & result1)

        add = Function(a, b) a + b
        Dim result2 As Integer = add(3, 5)
        Console.WriteLine("使用匿名方法的结果: " & result2)
    End Sub
    Function AddNumbers(ByVal a As Integer, ByVal b As Integer) As Integer
        Return a + b
    End Function
End Module

使用Lambda表达式

Module Module1
    Delegate Function AddDelegate(ByVal a As Integer, ByVal b As Integer) As Integer
    Sub Main()
        Dim add As AddDelegate = Function(a, b) a + b
        Dim result As Integer = add(3, 5)
        Console.WriteLine("使用Lambda表达式的结果: " & result)
    End Sub
End Module