Lamda表达式
1.lamda 表达式的演变过程
我们先来看下从 .Net Framework1.0到 .Net Framework3.0,委托传入参数的演变过程
//lamda 表达式的演变过程 { //.net Framework 1.0 只能传入已经定义的方法 CustomDelegate del = new CustomDelegate(DoNothing); CustomDelegateWith de = new CustomDelegateWith(DoSomething); } { //.net Framework 2.0 //可以传入delegate匿名方法 CustomDelegate del = new CustomDelegate(delegate() { Console.WriteLine("Do Nothing"); }); CustomDelegateWith de = new CustomDelegateWith( delegate(int id, string name) { Console.WriteLine("id:" + id + ",name:" + name); }); } { //.net Framework 3.0 //可以传入Lamda表达式 CustomDelegate del = new CustomDelegate(() => { Console.WriteLine("123"); }); CustomDelegateWith de = new CustomDelegateWith( (int id, string name) => { Console.WriteLine("id:" + id + ",name:" + name); }); } { //.net Framework 3.0 //可以传入Lamda表达式,做出一些变形 CustomDelegate del = () => { Console.WriteLine("123"); };//可以省略new CustomDelegate(); CustomDelegate del1 = () => Console.WriteLine("123");//如果方法体语句只有一行,可以省略方法体的{} CustomDelegateWith de = (int id, string name) => Console.WriteLine("id:" + id + ",name:" + name); ; }
从以上代码可以看出,.net Framework 1.0委托参数只能传入已经定义的方法,.net Framework 2.0 可以传入delegate匿名方法,到了.net Framework 3.0就可以传入Lamda表达式
lamda表达式是实例化委托的参数,lamda的本质是一个匿名的方法
从IL层面来讲,Landa在编译时会生成一个密封的私有类,里面定义了了lamda的匿名方法
但是Lamda表达式不仅仅局限为匿名的方法,如下代码所示,Lamda表达式还可以是表达式目录树
//lamda表达式除了作为委托参数使用外,还可以用作表达式目录树 { //此时的lamda表达式是一个表达式目录树,一种二叉树结构 Expression<Action<int, string>> exp = (id, name) => Console.WriteLine("id:" + id + ",name:" + name); }
2.Action和Func的使用
Action和Func是微软自定义的泛型委托,委托的样式变形很多,基本上满足了我们日常对委托的使用需要。那么什么时候用Action?什么时候用Func呢?
Action:传入0到16个参数,并且无返回值的委托
Func:传入0到16个参数,并且有返回值的委托
获取委托的返回值可以通过委托.Invoke()方法。
Action和Func委托使用代码如下
{ Action<string> a1 = name => Console.WriteLine(name); Func<int, string> f1 = (i) => { return i.ToString(); }; string gh = f1.Invoke(3);//获取委托的返回值 }
3.为什么会有Action和Func委托
我们先来看看从 .Net Framework1.0到 .Net Framework3.0,多线程的发展变化情况。
{ //.Net framwork 1.0 多线程 ParameterizedThreadStart thstart = (o) => { Console.WriteLine("ParameterizedThreadStart线程"); }; Thread thread = new Thread(thstart); thread.Start(); } { //.Net framwork 2.0 多线程 WaitCallback wait = (o) => { Console.WriteLine("WaitCallback线程"); }; ThreadPool.QueueUserWorkItem(wait); } { //.Net framwork 3.0 多线程 Action<object> action = o => Console.WriteLine(o.ToString()); Task task = new Task(action,"123"); task.Start(); }
从多线程的发展来看从1.0到3.0都用到了委托,委托的类型也是各式各样的,今后如果继续新增委托,对于我们开发和学习非常困难,因此,为了规范委托,微软创建了Action和Func两个通用委托