匿名方法、lambda

来源:互联网 发布:软件测试毕业总结 编辑:程序博客网 时间:2024/05/29 16:29

一、匿名方法
委托作为函数指针要指向一个方法,类似前面那种写法,定义函数签名、按照签名编写方法、最后委托指向这个方法,但很多时候没有必要这么繁琐,因为这个方法只有这个Delegate会用,而且往往只会用一次,这时使用匿名方法最合适。类似javascript中函数的写法:
Func<int, string, bool> d4 = delegate (int i, string str) {
  Console.WriteLine(i + "+" + str);
  return false;
};
var r1 = d4(4, "4");
Console.WriteLine(r1);
二、lambda
lambda表达式属于函数式编程的形式,在EF等场合会经常使用,labmda经常用的“=>”符号读作goes to。
基于匿名方法一步步简化可推导出lambda的写法:
//1 匿名方法
Func<int, int> f1 = delegate (int i) { Console.WriteLine(i); return 0; };
f1(1);
//2 省略delegate
Func<int, int> f2 = (int i) => { Console.WriteLine(i); return 0; };
f2(2);
//3 省略参数类型
Func<int, int> f3 = (i) => { Console.WriteLine(i); return 0; };
f3(3);
//4 如果是单个参数,省略小括号
Func<int, int> f4 = i => { Console.WriteLine(i); return 0; };
f4(4);
//5 如果只有一行代码,省略 大括号  
Func<int, int> f5_1 = i => { return i + 1; };
Func<int, int> f5_2 = i => i + 1;

三、自定义集合扩展方法
自定义集合扩展方法MyWhere如下,扩展方法必须位于静态类中:
static class MyWhereExt {
  public static IEnumerable<T> MyWhere<T>(this IEnumerable<T> data, Func<T, bool> func) {
    List<T> result = new List<T>();
    foreach (T item in data) {
      if (func(item)) {
        result.Add(item);
      }
    }
    return result;
  }
}
MyWhere对IEnumberable类型进行了扩展,List、数组等实现了这个接口的数据类型就都可以使用MyWhere了,筛选规则通过委托func传入,可以对各种集合进行自定义筛选,比如int数组:
int[] nums = new int[] { 3, 5, 7, 8 };
IEnumerable<int> r1 = nums.MyWhere<int>(i => i < 7);
foreach (var item in r1) {
  Console.WriteLine(item);
}
学习自定义MyWhere,是为了对后续的.net自带集合扩展方法有初步了解。

学习资料:如鹏网.net提高班http://www.rupeng.com/News/10/4603.shtml

原创粉丝点击