C#中有很多易混淆的關鍵詞,例如delegate,Func, Action和 Predicate。Func, Action和 Predicate本質上都是delegate,下面看一下delegate概念。
1 delegate概念
delegate本質上就是一個指向函數的指針,可以指向不同的函數,只要函數的簽名和代理一致即可。
2 delegate應用
其實Func, Action, Predicate等都是delegate,只是特殊的delegate而已。delegate的巧妙應用,可以大大簡化代碼和提高靈活性。下面有一段Javascript代碼,JS中經常使用數組的each方法來遍歷數組并對其進行處理,如下所示:
1
2
3
4
5
|
var arr = [ "one" , "two" , "three" , "four" ]; $.each(arr, function(){ alert( this ); }); //上面這個each輸出的結果分別為:one,two,three,four |
那么在C#中如何通過delegate來定義一個數組each方法呢,可以通過傳入方法來實現靈活的邏輯處理,靜態ListEx類下有一個靜態的Each方法,定義如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
public static T[] Each<T>(T[] source, Func<T, T> function) { T[] ret = new T[source.Length]; int i = 0; foreach (T item in source) { ret[i]=function(item); i++; } return ret; } |
那么我們可以定義一個字符串數組,并定義一個delegate作為函數參數進行傳入,調用ListEx.Each方法:
1
2
3
4
5
|
var arr = new string []{ "one" , "two" , "three" , "four" }; var newArr= ListEx.Each< string >(arr, delegate ( string x){ x=x+ "_do" ; return x; }); |
當然可以用表達式進行簡化:
1
|
var newArr2 = ListEx.Each< string >(newArr, ( string x) => x = x + "_do" ); |
我們也可以定義一個Where方法來過濾數組:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public static IList<T> Find<T>(IList<T> source, Predicate<T> predicate) { List<T> ret = new List<T>(); foreach (T item in source) { if (predicate(item)) { ret.Add(item); } } return ret; } public static T[] Where<T>(T[] source, Predicate<T> predicate) { IList<T> list=source.ToList<T>(); IList<T> retList= Find<T>(list, predicate); return retList.ToArray<T>(); } |
調用如下:
1
|
var newArr3 = ListEx.Where< string >(arr, x => x == "two" ); |
3 區別概述
- Func是必須指定返回值的代理;
- Action為返回值為void的代理;
- Predicate為返回值為bool的代理;
以上就是本文的詳細內容,希望對大家的學習C#程序設計有所幫助。