Func<T>、Action<T> 的區別于說明
一、Func
Func是一個.Net內置的委托。
Func<Result>,Func<T1,Result>是一個.Net內置的泛型委托。
1
2
3
4
5
|
Func<TResult> Func<T,TResult> Func<T1,T2,TResult> Func<T1,T2,T3,TResult> Func<T1,T2,T3,T4,TResult> |
它有5種形式,只是參數個數不同;第一個是無參數,但是有返回值;
下面是一個簡單的普通委托來傳方法的示例。
1
2
3
4
5
6
7
8
9
10
11
|
private delegate string Say(); public static string SayHello() { return "Hello" ; } static void Main( string [] args) { Say say = SayHello; Console.WriteLine(say()); Console.ReadKey(); } |
所以,在有時候,我們不知道一個接口同時要做什么操作的時候,我可以給它留一個委托。
為了更方便,.Net直接默認有了委托。我們再來試試.Net默認帶的委托。
1
2
3
4
5
6
7
8
9
10
|
public static string SayHello() { return "Hello" ; } static void Main( string [] args) { Func< string > say = SayHello; Console.WriteLine(say()); Console.ReadKey(); } |
如果需要參數的,還可以這樣傳一份。
1
2
3
4
5
6
7
8
9
10
11
|
public static string SayHello( string str) { return str + str; } static void Main( string [] args) { Func< string , string > say = SayHello; string str = say( "abc" ); Console.WriteLine(str); //輸出abcabc Console.ReadKey(); } |
二、Action
Action<T>的用法與Func幾乎一樣,調用方法也類似。
1
2
3
4
5
|
Action Action<T> Action<T1,T2> Action<T1,T2,T3> Action<T1,T2,T3,T4> |
1
2
3
4
5
6
7
8
9
10
11
|
private delegate string Say(); public static void SayHello( string str) { Console.WriteLine(str); } static void Main( string [] args) { Action< string > say = SayHello; say( "abc" ); Console.ReadKey(); } |
三、Func與Action的區別
Func與Action作用幾乎一樣。只是
Func<Result>有返回類型;
Action<T>只有參數類型,不能傳返回類型。所以Action<T>的委托函數都是沒有返回值的。
四、Func與Action都支持Lambda的形式調用
還是以一個輸入后,返回重復一次的值作為示例。
1
2
|
Func< string , string > say = m => m + m; Console.WriteLine(say( "abc" )); //輸出abcabc |
五、最常見到Func的地方
通常我們最常見到Func是在方法的參數里如下面這樣:
string XXX(Func<string, string>)
咱們來看看Linq里面的其中一個Sum:
public static int Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector);
里面看到兩點:
1、擴展方法,與這篇文章無關(擴展的是IEnumerable<TSource>,主要是為了能夠實現IEnumerable<TSource>接口的集合.出函數)。
2、Func<TSource, int> selector這個參數。
嘗試寫一個Linq的First函數吧,命名為First2。Linq源代碼里有很多異常情況處理,好多設計模式,可惜我不懂,只提取簡單邏輯了。
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
|
namespace ConsoleApplication2 { static class Extend { public static TSource First2<TSource>( this IEnumerable<TSource> source, Func<TSource, bool > predicate) { //.Net本身的源代碼好多異常情況處理,好多設計模式,我也不懂,只提取邏輯 foreach (TSource item in source) { if (predicate(item)) { return (item); } } throw new Exception( "不存在滿足條件的第一個元素!" ); } } class Program { static void Main( string [] args) { List< int > ListInt = new List< int >(){ 1, 2, 3, 4, 5 }; int k = ListInt.First2(m => m > 4); //輸出5 Console.WriteLine(k); Console.ReadKey(); } } } |
以上所述是本文的全部內容,有問題的可以和小編聯系,謝謝對服務器之家的支持!
原文鏈接:http://www.cnblogs.com/kissdodog/p/5674629.html