標籤:
我們先看一個上一章的委託的例子:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Test 8 { 9 class Program10 {11 static void Main(string[] args)12 {13 new Program();14 15 Console.ReadKey();16 }17 18 public delegate void AddDelegate(float a, int b);19 20 public Program()21 {22 AddDelegate add = addFunc;23 24 add(11.11f, 123);25 }26 27 private void addFunc(float a, int b)28 {29 double c = a + b;30 Console.WriteLine(c);31 }32 }33 }
Action:
Action可以看做C#為我們提供的內建的沒有傳回值的委託,用在第一個例子裡可以去掉委託的聲明,代碼如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Test 8 { 9 class Program10 {11 static void Main(string[] args)12 {13 new Program();14 15 Console.ReadKey();16 }17 18 public Program()19 {20 //指定好參數數量和類型即可立即使用, 無需顯示的定義委託21 Action<float, int> add = addFunc;22 23 add(11.11f, 123);24 }25 26 private void addFunc(float a, int b)27 {28 double c = a + b;29 Console.WriteLine(c);30 }31 }32 }
同時,匿名函數和Lambda的寫法也是允許的,詳情可以查看上一篇筆記。
Func:
類似Action,Func是C#為我們提供的內建的具有傳回值的委託,而傳回值的類型為最後一個被指定的類型,請看下面的例子:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Test 8 { 9 class Program10 {11 static void Main(string[] args)12 {13 new Program();14 15 Console.ReadKey();16 }17 18 public Program()19 {20 //指定好參數數量和類型即可立即使用, 無需顯示的定義委託21 //對於 Func 委託來說, 最後指定的類型為返回的類型22 Func<float, int, string> add = addFunc;23 24 string result = add(11.11f, 123);25 Console.WriteLine(result);26 }27 28 private string addFunc(float a, int b)29 {30 double c = a + b;31 Console.WriteLine(c);32 return "hello: " + c.ToString();33 }34 }35 }
Predicate:
該委託專門用於過濾集合中的元素,下面我們看一個例子,保留數組中的正整數:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Test 8 { 9 class Program10 {11 static void Main(string[] args)12 {13 new Program();14 15 Console.ReadKey();16 }17 18 public Program()19 {20 //指定的類型為需要過濾的數組的元素類型21 Predicate<int> filter;22 filter = IntFilter;23 24 int[] nums = new int[8]{12, -33, -89, 21, -15, 29, 40, -52};25 //開始進行過濾, 返回 true 表示留下當前元素26 int[] result = Array.FindAll(nums, filter);27 28 for(int i = 0; i < result.Length; i++)29 {30 Console.WriteLine(result[i]);31 }32 }33 34 private bool IntFilter(int i)35 {36 if (i >= 0)37 {38 return true;39 }40 return false;41 }42 }43 }
委託學習續:Action、Func和Predicate