C# Action委托


  最近碰到了很多關於Action的一些代碼,稍微看了下用法

  Action的作用是封裝一個函數,且該方法沒有返回值(有返回值的函數無法被Action封裝)。同時Action還支持不同參數數量的函數,通過泛型來實現。Action<T>代表Action所封裝的函數是有一個參數,參數類型為T。同理,Action最多支持16個參數的函數委托,不過每個參數的數據類型都要寫到泛型里。

  不同參數類型的Action聲明:

  Action

  Action<T>

  Action<T,T>

  Action<T,T,T> ......

 

  Action其實是一個委托delegate,如果我們使用delegate去封裝一個函數的話,首先是需要進行委托聲明的,如下面的代碼

 1 namespace Delegate_Action
 2 {
 3     //自定義委托聲明
 4     public delegate void delegateFuntion();
 5     class Program
 6     {
 7         static void Main(string[] args)
 8         {
 9             Test t = new Test();
10             delegateFuntion myFunction = t.Function;    //函數封裝
11             myFunction();
12 
13             return;
14         }
15     }
16 
17     class Test
18     {
19         public void Function()
20         {
21             Console.WriteLine("Test Function!");
22         }
23     }
24 }

  可以看到第4行進行了委托聲明的動作,而為了操作簡便,Action委托就可以免去這一步驟

  如果用Action進行封裝的話,代碼如下

 1 namespace Delegate_Action
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             Test t = new Test();
 8             Action myAction = t.Function;   //直接到位
 9             myAction();
10 
11             return;
12         }
13     }
14 
15     class Test
16     {
17         public void Function()
18         {
19             Console.WriteLine("Test Function!");
20         }
21     }
22 }

  同時Action支持委托和匿名函數

 1 namespace Delegate_Action
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             Test t = new Test();
 8             Action myAction = delegate() { Console.WriteLine("Delegate Function!"); };   //直接到位
 9             myAction();
10 
11             return;
12         }
13     }

 

  最后就是Action可以通過參數的形式傳遞函數,這樣就可以將Action用作回調函數(個人感覺用處最多的地方),代碼如下

 1 namespace Delegate_Action
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             Test t = new Test(CallBackFuntion);
 8             t.Function();
 9 
10             return;
11         }
12 
13         static void CallBackFuntion()
14         {
15             Console.WriteLine("Program Call Back Function!");
16         }
17     }
18 
19     class Test
20     {
21         Action callBack;
22 
23         public Test(Action cb)
24         {
25             callBack = cb;
26         }
27 
28         public void Function()
29         {
30             Console.WriteLine("Test Function!");
31             callBack();  
32         }
33     }
34 
35     //結果:
36     //      Test Function!
37     //      Program Call Back Function!
38 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM