在 2.0 之前的 C# 版本中,声明委托的唯一方法是使用命名方法。 C# 2.0 引入了匿名方法,而在 C# 3.0 及更高版本中,Lambda 表达式取代了匿名方法,作为编写内联代码的首选方式。
delegate int cc (int i, int j);
class Program
{
static void Main(string[] args)
{
//委托
cc a = new cc(add);
Console.WriteLine(a(1, 5));
class Program
{
static void Main(string[] args)
{
//委托
cc a = new cc(add);
Console.WriteLine(a(1, 5));
//匿名方法
cc b = delegate(int x, int y)
{
return x - y;
};
Console.WriteLine(b(1, 5));
cc b = delegate(int x, int y)
{
return x - y;
};
Console.WriteLine(b(1, 5));
//Lambda表达式
cc c = (x, y) => x * y;
Console.WriteLine(c(1, 5));
cc c = (x, y) => x * y;
Console.WriteLine(c(1, 5));
Console.ReadKey();
}
public static int add(int x, int y)
{
return x + y;
}
}
}
public static int add(int x, int y)
{
return x + y;
}
}
若要创建 Lambda 表达式,需要在 Lambda 运算符 => 左侧指定输入参数(如果有),然后在另一侧输入表达式或语句块。 例如,lambda 表达式 x => x * x 指定名为 x 的参数并返回 x 的平方值。 如上面的示例所示,你可以将此表达式分配给委托类型:
"Lambda表达式"是一个特殊的匿名函数,是一种高效的类似于函数式编程的表达式,Lambda简化了开发中需要编写的代码量。