.NET 中的匿名方法和 Lambda 表达式






4.36/5 (7投票s)
.NET 中的匿名方法和 Lambda 表达式
引言
本文旨在提供 C# 和 Visual Basic.NET 中匿名方法和 Lambda 表达式的基本概念。
匿名方法
匿名方法是一个未命名的方法,它只包含方法体,没有名称或标识符,并且由委托调用。匿名方法被引用或关联到委托,不能在不使用委托的情况下显式或直接调用。匿名方法的方法体由花括号包围,并包含内联代码。当我们有一个小型任务或操作,并且我们想以内联方式执行它时,就使用匿名方法。匿名方法与命名方法相似,但主要区别在于命名方法有一个指定的名称、一个访问修饰符、一个返回类型、一个包含零个或多个参数的参数列表以及一个包含代码块的方法体,而匿名方法是一个未命名的方法,它没有名称或标识符,没有访问修饰符,也没有返回类型,它的声明总是以关键字 delegate 开头,后面跟着参数列表和方法体。匿名方法的参数列表可以包含零个或多个参数,它们由小括号包围。匿名方法不需要指定其返回类型,但它允许我们使用 return 语句返回值。命名方法可以通过简单地调用其名称来直接或显式调用,而匿名方法不能像命名方法那样直接或显式调用,但可以通过委托隐式调用。要调用匿名方法,需要声明委托的实例,并将匿名方法引用或关联到该实例。当匿名方法被引用或关联到委托的实例时,我们通过调用该实例来调用它,如果它带有参数,则向其传递值。匿名方法可以通过将其作为参数分配给委托的实例来引用或关联到该实例。当匿名方法作为参数分配给委托的实例时,委托的实例存储其内存地址,并且该方法被引用或关联到它。
委托可以引用和调用与其参数匹配的匿名方法。这意味着委托的参数和被引用或关联的匿名方法的参数必须相同。例如,如果一个匿名方法不带任何参数,那么它可以被不带任何参数的委托实例引用和调用;同样,如果一个匿名方法带一个整数参数,那么我们必须声明一个带一个整数参数的委托实例,依此类推。下面是声明无参数匿名方法的通用语法:
C# 语法
instDelegate = delegate() {-Body of the anonymous method-};
或者
instDelegate = delegate()
{
[-Body of the anonymous Method-]
};
VB.NET 语法
instDelegate = Sub() [-Body of the anonymous method-]
或者
instDelegate = Sub()
-------------------------
[-Body of the Anonymous Method-]
-------------------------
End Sub
在上述声明中,`instDelegate` 是一个无参数委托的实例,它不带任何参数,并引用一个无参数匿名方法。`[-Body of the Anonymous Method-]` 表示匿名方法的方法体,其中包含内联代码。下面是声明带指定数量参数的匿名方法的通用语法:
C# 语法
instDelegate = delegate(ParametersList) {[-Body of Method-]};
或者
instDelegate = delegate(ParametersList)
{
[-Body of Method-]
};
VB.NET 语法
instDelegate = Sub(ParametersList) [-Body of Method-]
或者
instDelegate = Sub(ParametersList)
------------------------------------------
[-Body of Method-]
------------------------------------------
End Sub
在上面的声明中,`instDelegate` 是一个参数化委托的实例,它根据其引用和调用的方法接受一个或多个参数,例如,如果匿名方法接受一个整数参数,那么它必须接受一个整数参数;同样,如果匿名方法接受一个整数和一个浮点参数,那么它必须接受一个整数和一个浮点参数,依此类推。`ParametersList` 表示匿名方法的参数列表,其中包含一个或多个参数。`[-Body of Method-]` 表示匿名方法的方法体,其中包含内联代码。
程序 # 1
编写一个程序,使用无参数匿名方法在屏幕上显示一条消息。
C# 程序
using System;
namespace ProgramNamespace
{
//Define a delegate reference type that references or associates a
//parameter-less anonymous method having no parameters and
//does not return value
delegate void MyDelegate();
public class MainProgramClass
{
public static void Main()
{
//Declare an instance of the delegate MyDelegate reference type
MyDelegate instDelegate;
//References or associates the parameter-less anonymous method
//with the instance instDelegate of the delegate by assigning the
//anonymous method to it as parameter using a single line
//assignmnet
instDelegate = delegate() { Console.WriteLine("Hello"); };
//We can also reference or associate the anonymous method with
//the instance instDelegate of the delegate by assigning the
//anonymous method to it as parameter using the multiple lines
//assignment
instDelegate = delegate()
{
Console.WriteLine("Hello");
};
//Invoke the anonymous method that displays a message on the screen
instDelegate();
Console.WriteLine("Press any key to exit ");
Console.ReadKey();
}
}
}
Visual Basic.NET 程序
Namespace ProgramNamespace
'Define a Delegate reference type that references or associates a
'parameter-less anonymous method having no parameters and
'does not return value
Delegate Sub MyDelegate()
Public Class MainProgramClass
Public Shared Sub Main()
'Declare an instance of the delegate MyDelegate reference type
Dim instDelegate As MyDelegate
'References or associates the parameter-less anonymous method
'with the instance instDelegate of the delegate by assigning the
'anonymous method to it as parameter using a single line
'assignmnet
instDelegate = Sub() Console.WriteLine("Hello")
'We can also reference or associate the anonymous method with
'the instance instDelegate of the delegate by assigning the
'anonymous method to it as parameter using the multiple lines
'assignment
instDelegate = Sub()
Console.WriteLine("Hello")
End Sub
'Invoke the anonymous method that displays a message on the screen
instDelegate()
Console.WriteLine("Press any key to exit ")
Console.ReadKey()
End Sub
End Class
End Namespace
上面的程序使用匿名方法在屏幕上显示 Hello。在程序中,我们定义了一个名为 `MyDelegate` 的委托引用类型,它没有参数也不返回值。在程序的 `main` 方法中,我们声明了一个 `MyDelegate` 委托引用类型的实例 `instDelegate`,并通过分配一个没有参数也不返回任何值的匿名方法来实例化它。然后使用 `MyDelegate` 引用类型的实例 `instDelegate` 并调用所引用的匿名方法。
程序 # 2
编写一个程序,使用匿名方法添加两个整数值。匿名方法接受两个整数参数并将其和返回到调用点。
C# 程序
using System;
namespace ProgramNamespace
{
//Define a Delegate reference type that references or associates an
//anonymous method having two integer parameters and return an
//integer value
delegate int MyDelegate(int x, int y);
public class MainProgramClass
{
public static void Main()
{
//Declare an instance of the delegate MyDelegate reference type
MyDelegate instDelegate;
//References or associates the parameterized anonymous method
//with the instance instDelegate of the delegate by assigning the
//anonymous method to it as parameter using a single line assignmnet
instDelegate = delegate(int x, int y) {return x + y;};
//We can also reference or associate the anonymous method with
//the instance insDelegate by assigning the anonymous method to it
//as parameter using the multiple lines assignment
instDelegate = delegate(int x, int y)
{
return x + y;
};
//Invoke the anonymous method and pass two integer values to it
//and declare an integer variable to store the result of the
//anonymous method
int result = instDelegate(2, 3);
//Display the result of the anonymous method
Console.WriteLine("The sum of two values = " + result);
Console.WriteLine("Press any key to exit ");
Console.ReadKey();
}
}
}
Visual Basic.NET 程序
Namespace ProgramNamespace
'Define a Delegate reference type that represents an anonymous
'method having two integer parameters and integer return type
Delegate Function MyDelegate(x As Integer, y As Integer) As Integer
Public Class MainProgramClass
Public Shared Sub Main()
'Declare an instance of the delegate MyDelegate reference type
Dim instDelegate As MyDelegate
'References or associates the parameterized anonymous method
'with the instance instDelegate of the delegate by assigning the
'anonymous method to it as parameter using a single line assignmnet
instDelegate = Function(x As Integer, y As Integer) x + y
'We can also reference or associate the anonymous method with
'the instance insDelegate by assigning the anonymous method to it
'as parameter using the multiple lines assignment
instDelegate = Function(x As Integer, y As Integer)
Return (x + y)
End Function
'Invoke the anonymous method and pass two integer values to it
'and declare an integer variable to store the result of the anonymous method
Dim result As Integer = instDelegate(2, 3)
'Display the result of the anonymous method
Console.WriteLine("The sum of two values = " & result)
Console.WriteLine("Press any key to exit ")
Console.ReadKey()
End Sub
End Class
End Namespace
Lambda 表达式
Lambda 表达式是匿名方法的简化形式,用于以表达式的形式编写匿名方法,而无需其声明。它将匿名方法分为两部分,并通过在它们之间放置一个运算符(称为 Lambda 运算符)来构成一个表达式。匿名方法的声明总是以关键字 delegate 开头,后跟参数列表及其方法体。匿名方法的参数列表可以包含零个或多个参数,并且每个参数都需要其数据类型规范,例如,如果匿名方法接受一个或多个参数,那么我们必须指定每个参数的数据类型。Lambda 表达式减少了关键字 delegate 和参数的数据类型规范,它允许我们编写匿名方法,而无需使用关键字 delegate 及其参数的数据类型规范。Lambda 表达式允许我们选择声明匿名方法的所有输入参数及其数据类型规范,或者只是提供输入参数的名称而不带数据类型规范。编译器会自动从用法中管理输入参数的数据类型。Lambda 表达式包含由一个运算符分隔的两部分,该运算符称为 Lambda 运算符。Lambda 运算符是等号运算符和大于号运算符的组合,表示为 =>。Lambda 运算符放置在 Lambda 表达式的两部分之间,其中 Lambda 表达式的左侧部分表示由小括号包围的匿名方法的输入参数列表,Lambda 表达式的右侧部分表示匿名方法的方法体。匿名方法的方法体可以包含单个或多个语句。如果匿名方法的方法体包含单个语句,那么它通常与 Lambda 运算符写在同一行上;如果匿名方法的方法体包含多个语句,那么它像匿名方法一样由花括号 { } 包围。
要使用 Lambda 表达式编写匿名方法,它将匿名方法分为两部分,例如参数列表和匿名方法的方法体。Lambda 表达式的左侧部分接受匿名方法的输入参数,但不包含其参数数据类型规范。它只接受输入参数的名称,无需指定它们的数据类型,因为编译器会自动从使用情况推断输入参数的数据类型。Lambda 表达式的右侧部分接受匿名方法的方法体。Lambda 表达式在 C# 3.0 中引入。以下是声明 Lambda 表达式的通用语法:
([InputParametersList]) => {[BodyOfAnonymousMethod]};
上述语法是 Lambda 表达式的通用语法,它将匿名方法写成两部分并构成一个表达式。Lambda 表达式的左侧部分是 `([ParametersList])`,表示匿名方法的输入参数数量;`=>` 符号表示 Lambda 运算符;Lambda 表达式的右侧部分是 `[BodyOfAnonymousMethod]`,表示匿名方法的方法体。如果匿名方法的方法体包含多个语句,则方法体由花括号包围,上述语法可以写成:
([InputParametersList]) => { [BodyOfAnonymousMethod] };
Or
([ParametersList]) =>
{
BodyOfAnonymousMethod
};
使用 Lambda 表达式的好处
Lambda 表达式是在程序中减少代码块并使其更易于理解的最佳选择。它降低了匿名方法的复杂性,使其变得更简单、更短。Lambda 表达式从匿名方法的声明中减少了 delegate 关键字及其参数的数据类型规范。Lambda 表达式的主要用途是访问 LINQ。如果我们要访问程序代码中的 LINQ,那么 Lambda 表达式是访问 LINQ 的最佳选择。
程序 # 3
编写一个程序,使用无参数匿名方法在屏幕上显示一条消息。匿名方法使用 Lambda 表达式。
C# 程序
using System;
namespace ProgramNamespace
{
//Define a delegate reference type that references or associates a
//parameter-less anonymous method in the form of a Lambda
//Expression having no parameters and does not return value
delegate void MyDelegate();
public class MainProgramClass
{
public static void Main()
{
//Declare an instance of the delegate MyDelegate reference type
MyDelegate instDelegate;
//References the Lambda Expression with the instance //instDelegate of the delegate
instDelegate = () => { Console.WriteLine("Hello"); };
//Invoke the Lambda Expression using the instance of the delegate
instDelegate();
Console.WriteLine("Press any key to exit ");
Console.ReadKey();
}
}
}