c# 带返回值的action_C#委托Action、ActionT、FuncT、PredicateT
一、Action
Action封裝的方法沒有參數也沒有返回值,聲明原型為:
1 public delegate void Action();
用法如下:
1 public void Alert()
2 {
3 Console.WriteLine("這是一個警告");
4 }
5
6 Action t = new Action(Alert); // 實例化一個Action委托
7 t();
如果委托的方法里的語句比較簡短,也可以用Lambd表達式直接把方法定義在委托中,如下:
1 Action t = () => { Console.WriteLine("這是一個警告"); };
2 t();
二、Action
Action是Action的泛型實現,也是沒有返回值,但可以傳入最多16個參數,兩個參數的聲明原型為:
1 public delegate void Action(T1 arg1, T2 arg2);
用法如下:
1 private void ShowResult(int a, int b)
2 {
3 Console.WriteLine(a + b);
4 }
5
6 Action t = new Action(ShowResult);//兩個參數但沒返回值的委托
7 t(2, 3);
同樣也可以直接用Lambd表達式直接把方法定義在委托中,代碼如下:
1 Action t = (a,b) => { Console.WriteLine(a + b); };
2 t(2, 3);
三、Func
Func委托始終都會有返回值,返回值的類型是參數中最后一個,可以傳入一個參數,也可以最多傳入16個參數,但可以傳入最多16個參數,兩個參數一個返回值的聲明原型為:
1 public delegate TResult Func(T1 arg1, T2 arg2);
用法如下:
1 public bool Compare(int a, int b)
2 {
3 return a > b;
4 }
5
6 Func t = new Func(Compare);//傳入兩個int參數,返回bool值
7 bool result = t(2, 3);
同樣也可以直接用Lambd表達式直接把方法定義在委托中,代碼如下:
1 Func t = (a, b) => { return a > b; };
2 bool result = t(2, 3);
四 、Predicate
Predicate委托表示定義一組條件并確定指定對象是否符合這些條件的方法,返回值始終為bool類型,聲明原型為:
1 public delegate bool Predicate(T obj);
用法如下:
1 public bool Match(int val)
2 {
3 return val > 60;
4 }
5
6 Predicate t = new Predicate(Match); //定義一個比較委托
7 int[] arr = { 13, 45, 26, 98, 3, 56, 72, 24 };
8 int first = Array.Find(arr, t); //找到數組中大于60的第一個元素
同樣也可以直接用Lambd表達式直接把方法定義在委托中,代碼如下:
1 Predicate t = val => { return val > 60;}; //定義一個比較委托
2 int[] arr = { 13, 45, 26, 98, 3, 56, 72, 24 };
3 int first = Array.Find(arr, t); //找到數組中大于60的第一個元素
總結:
如果要委托的方法沒有參數也沒有返回值就想到Action
有參數但沒有返回值就想到Action
無參數有返回值、有參數且有返回值就想到Func
有bool類型的返回值,多用在比較器的方法,要委托這個方法就想到用Predicate
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的c# 带返回值的action_C#委托Action、ActionT、FuncT、PredicateT的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab中删除照片_如何使用matl
- 下一篇: fasttext 安装_fasttext