LINQ中的Func委托

一个使用了Func委托的小例子
1
2
3
4
5
6
7
8
//建立一个整型数组
int [] intArray = new int [] { 0, 1, 2, 3 };
//声明Func委托, 判断是不是奇数
Func< int , bool > IsOdd = i => ((i & 1) == 1);
//执行查询操做, 别忘了具备"延迟特性"
IEnumerable< int > items = intArray.Where(IsOdd);
//显示结果
foreach ( int item in items)
Console.WriteLine(item);

       程序如我所愿的找出了intArray中的奇数有哪些. 但背后Func委托实质上为咱们省去了哪些步骤呢? 我首先研究了LINQ查询中的委托.html

LINQ中where查询的原型

       在个人一篇介绍lambda表达式的博客中有一个例子. 例子描述了这样一种状况: 有一个int型数组, 须要找出其中的奇数, 偶数等等等. 下面再贴出这个例子有用部分的完整代码:数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections;
namespace LinqTest
{
class Program
{
public class Commom
{
//命名一个委托方法
public delegate bool IntFilter( int i);
//筛选出符合委托方法所要求的int, 返回一个int[]
public static int [] FilterArrayOfInts( int [] ints, IntFilter filter)
{
ArrayList aList = new ArrayList();
foreach ( int i in ints)
if (filter(i))
aList.Add(i);
return ( int [])aList.ToArray( typeof ( int ));
}
}
//根据须要, 本身定义筛选方法
public class MyIntFilter
{
//本身定义的筛选方法1: 检测是不是奇数
public static bool IsOdd( int i)
{
return ((i & 1) == 1);
}
//本身定义的筛选方法2: 检测是不是偶数
public static bool IsEven( int i)
{
return ((i & 1) != 1);
}
//...根据须要还能够定义其它筛选方法
}
static void Main( string [] args)
{
int [] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//筛选出奇数
int [] oddNums = Commom.FilterArrayOfInts(nums, i => ((i & 1) == 1));
foreach ( int i in oddNums)
Console.Write(i + " " );
}
}
}

       这个例子本身定义的一个Commom类, 并有一个筛选出必定要求的方法FilterArrayOfInts, 若是咱们使用扩展方法将FilterArrayOfInts扩展到int[]类型, 将FilterArrayOfInts方法名改为where, 那就颇有趣了, 那么最后筛选出奇数的代码就是这个样子的:ide

1
2
int [] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//筛选出奇数
int [] oddNums = nums. where (i => ((i & 1) == 1));

       是否是很是像LINQ中的where? 其实就是这么个道理.spa

Func委托的做用

       <LINQ技术详解>里面是这么说的: 能够防止开发者显式声明委托类型.3d

       什么意思呢? 上面的代码仍是有用的, 能够这样理解, 上面代码中MyIntFilter类中定义了不少筛选必定条件整数的方法, 有方法就会有方法返回类型, 方法若是有参数就会还有参数类型. 以下:code

1
2
3
4
5
6
7
8
9
//本身定义的筛选方法1: 检测是不是奇数
public static bool IsOdd( int i)
{
return ((i & 1) == 1);
}
//本身定义的筛选方法2: 检测是不是偶数
public static bool IsEven( int i)
{
return ((i & 1) != 1);
}

       Func委托将定义这些方法的代码变得简单, 若是是上面的这两个方法, 利用Func委托只须要这样写:orm

1
Func< int , bool > IsOdd = i => ((i & 1) == 1);
Func< int , bool > IsEven = i => ((i & 1) != 1);

       这样子在写法上就比较简单, 而且一看就明了代码是什么意思.htm


http://www.cnblogs.com/technology/archive/2011/02/23/1962252.htmlblog

相关文章
相关标签/搜索