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