Lambda 表达式
2019-04-11 本文已影响12人
你这样我很吃惊
Lambda
什么是Lambda表达式
- 简单来说,编程中提到的 lambda 表达式,通常是在需要一个函数,但是又不想费神去命名一个函数的场合下使用,也就是指匿名函数。
- 可以使用委托对象调用可由委托引用的方法,提供了一种传递代码块作为委托参数的技术。匿名方法是没有名称只有主体的方法。
- 在Lambda中您不需要指定返回类型,它是从方法主体内的 return 语句推断的。
如何使用Lambda表达式
一. Lambda表达式的由来:
- 基于委托创建Lambda表达式 以下代码将表述从 匿名函数—>最简化的Lambda 表达式的过程:
public delegate void NoReturnWithPara(int x,int y); //创建一个委托
class MyLamda
{
public static void Show()
{
NoReturnWithPara method0 = new NoReturnWithPara(ShowSomething); //将委托绑定方法
/*创建一个匿名函数 即 在实例化委托对象的时候 将函数内容写入初始化中*/
NoReturnWithPara method2 = new NoReturnWithPara(
delegate (int x, int y) //匿名方法
{
/*方法体*/
Console.WriteLine("delegate");
}
);
/*创建一个初始版Lambda表达式 优化上例部分内容 即 去除上例中 delegate关键字 改为 最后加入 => 符号*/
NoReturnWithPara method3 = new NoReturnWithPara(
(int x, int y) => //初形 Lambda
{
/*方法体*/
Console.WriteLine("delegate");
}
);
/*完整的 Lambda 出现 即 优化参数列表 参数类型不必明确声明 类型根据当前委托的参数类型 去除new实例过程*/
NoReturnWithPara method4 =
(x, y) => //参数列表 参数类型可以去除
{
/*方法体*/
Console.WriteLine("delegate");
};
/*优化上例部分内容 即 去除了{},但是方法体只能有一行内容*/
NoReturnWithPara method5 = new NoReturnWithPara(
(x, y) =>
/*方法体 一行*/
Console.WriteLine("delegate")
);
/*终极优化 方法体只能一行 ----- 类似简写委托 即 取消实例化 new过程 */
NoReturnWithPara method6 = (x, y) => /*方法体 一行*/ Console.WriteLine("delegate");
}
static void ShowSomething(int x, int y)
{
Console.WriteLine("ShowSomeThing");
}
}
如上 是带有参数的委托的Lambda表达式简化形式。还有另外一些写法就不一一阐述了。
- 以下写一个有参数 有返回值的Lambda写法
public delegate int WithReturnNoPara(int x);
class MyLamda
{
public static void Show()
{
WithReturnNoPara method11 =
(int a) =>
{
return a;
};
Console.WriteLine(method11(5));
//只有一个参数时 不需要括号 当只有一条方法体 返回数据无需 return 修饰
WithReturnNoPara method10 = x => x;
Console.WriteLine(method10(5));
}
}
如上 会打印得到值 5 如此为有参数又返回值的Lambda表达式
二.系统自带委托 Action Func的Lambda
- Action 无返回值类型
class MyLamda
{
public static void Show()
{
//一个系统自定义的委托
Action act1 = () => { Console.WriteLine("act1"); }; //无参 无返 lamda
act1();
//最多可以接受 16个参数 的委托 ,有参 无返
Action<string, int> act2 = (x, y) => { Console.WriteLine(x + "+" + y); };
act2("a", 5);
Action<string, int> act3 = (x, y) => Console.WriteLine("x + y"); //去掉{} 但只能写一句方法体
}
}
- Func 有返回值类型
class MyLamda
{
public static void Show()
{
//无参 有返回值 如此 返回2 返回值为唯一的<>中的类型 详情F12
Func<int> fun1 = () => 2;
Console.WriteLine(fun1()); //返回值为2
//有参 有返回值 如此 返回“abc” 返回值为<>中最后一个输入的类型 前三个为()中参数类型 最多16个参数 详情F12
Func<int,double,string,string> fun2 = (x,y,z) => "abc";
Console.WriteLine(fun2(2, 2, "2")); //结果为 abc
}
}
三.将函数当做参数传递
在开发中遇到需要将函数内容 当做参数传递的 也可使用这种方法传递 借助委托的Lambda
class MyLamda
{
public static void Show()
{
ShowSomething4(() => { Console.WriteLine("ShowSomething4"); }); //Action
ShowSomething4((x,y) => {return "ShowSomething4"; }); //Func
}
static void ShowSomething4(Action function)
{
function();
}
static void ShowSomething4(Func<int,int,string> function)
{
Console.WriteLine(function(5, 5));
}
}