C#中Action的使用

來源:互聯網
上載者:User

標籤:

在日常使用delegate時,我們通常需要顯示聲明一個名為XXX的委託,而在使用Action委託時,不必顯示定義一個封裝無參數過程的委託。

比如正常使用delegate:

 1 using System; 2  3 namespace MT 4 { 5     public delegate void ShowValue();//在這裡顯示聲明一個委託 6  7     public class Test 8     { 9         //在這裡有一個Test類,類中有一個void的方法,作用是輸出一個字串10         private string instanceName;11         public Test(string name)12         {13             this.instanceName = name;14         }15         public void DisplayToConsole()16         {17             Console.WriteLine(this.instanceName);18         }19     }20 21     public class Program22     {23         //在Main函數裡使用委託去調用這個方法24         static void Main(string[] args)25         {26             Test name = new Test("Sirius");27             ShowValue method = name.DisplayToConsole;28             method();29             Console.ReadKey();30         }31     }32 }

Action就是這麼個姿勢:

1 static void Main(string[] args)2 {3     Test name = new Test("Sirius");4     Action method = name.DisplayToConsole;5     method();6     Console.ReadKey();7 }

 

當然,Action也可以有簽名模板,Action<T>。

public void DisplayToConsole(string name){      Console.WriteLine(name);}
Action<string> method2 = name.DisplayToConsole;method2("123");Console.ReadKey();

順便貼一張MSDN的牛逼圖,這是我第一次看MSDN看到想笑……

 

代碼參考:https://msdn.microsoft.com/zh-cn/library/system.action(v=vs.110).aspx

C#中Action的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.