本文共 3624 字,大约阅读时间需要 12 分钟。
c#2.0引入匿名方法,不必创建单独的方法,因此减少了所需的编码系统开销。 常用于将委托和匿名方法关联,例如
1. 使用委托和方法关联:2. 使用委托和匿名方法关联:
this.btnRefresh.Click += delegate(object sender, EventArgs e) { BindData(); };毫无疑问,如果关联的方法是“一句话方法”的话,代码2更为简洁(实际上编译器在背后为我们创建了类似btnRefresh_Click的方法)。定义匿名方法时候,参数列表是可以省略的,编译器可以根据委托的签名来确定函数的签名。例如,delegate void Func(int x);//带参数Func f1= delegate (int p) { Console.Write(p); }// 不带参数Func f2 = delegate { Console.Write("he");} //编译器自动推断函数签名带int参数使用不带参数的匿名方法,注意问题 一是因为没有参数,所以在方法内就不能使用参数。 二是有些情况不能使用匿名方法,有ambiguous的问题,例如public Thread(ParameterizedThreadStart start); public Thread(ThreadStart start); 而// public delegate void ParameterizedThreadStart(object obj); // public delegate void ThreadStart();所以使用 Thread thread = new Thread( delegate { sh.LockMyself(); } );就会有问题Error The call is ambiguous between the following methods or properties: 'System.Threading.Thread.Thread(System.Threading.ThreadStart)' and 'System.Threading.Thread.Thread(System.Threading.ParameterizedThreadStart)' 编译器不知道应该将delegate { }这一匿名方法还原为哪个函数,解决方法是显式给定参数列表,让编译器知道你要用那个函数:Thread thread = new Thread( delegate() { sh.LockMyself(); } );Lambda表达式:Thread thread = new Thread( () => { sh.LockMyself(); } );
Lambda表达式为编写匿名方法提供了更简明的函数式的句法,但结果却在编写LINQ查询表达式时变得极其有用,因为它们提供了一个非常紧凑的而且类安全的方式来编写可以当作参数来传递,在以后作运算的函数。Lambda 表达式和 匿名方法 其实是一件事情。唯一的不同是:他们语法表现形式不同。Lambda 表达式是在语法方面的更进一步的进化。在本质上,他们是一件事情。他们的作用都是:产生方法。即:内联方法。 books是System.Collections.Generic.List类型, 即List<Book>, 有Find方法使用匿名方法: books.Find(delegate(Book book){return book.Price < 50;});使用Lambda表达式: books.Find(book=>book.Price<50);book是输入参数; =>读作Go to,是Lambda操作符;book.Price<50是表达式或者语句块。Lambda表达式中的输入参数省略参数类型,因为当前Find扩展方法对象是books,编译器会自动推断book参数属于BooK类型.对比另一个例子:
Lambda表达式式范例:
高阶函数(higher-order function)
是指把另一个函数作为参数或返回值的函数。
例如在System.Array类中就有许多静态的高阶函数,其中的ConvertAll方法可谓是最常用的高阶函数之一了:
Reference
转载地址:http://delum.baihongyu.com/