C#中的Action<>和Func<>

來源:互聯網
上載者:User

標籤:

其實他們兩個都是委託【代理】的簡寫形式。

一、【action<>】指定那些只有輸入參數,沒有傳回值的委託

Delegate的代碼:

[csharp] view plaincopy 
  1. public delegate void myDelegate(string str);  
  2. public static void HellowChinese(string strChinese)  
  3. {  
  4.     Console.WriteLine("Good morning," + strChinese);  
  5.     Console.ReadLine();  
  6. }  
  7.   
  8. myDelegate d = new myDelegate(HellowChinese);  
  9. d("Mr wang");  


用了Action之後呢:

 

[csharp] view plaincopy 
  1. public static void HellowChinese(string strChinese)  
  2. {  
  3.     Console.WriteLine("Good morning," + strChinese);  
  4.     Console.ReadLine();  
  5. }  
  6.   
  7. Action<string> action = HellowChinese;  
  8. action("Spring.");  

就是相當於省去了定義委託的步驟了。

 

二、func<> 這個和上面的那個是一樣的,區別是這個有傳回值!

[csharp] view plaincopy 
    1. public static string HelloEnglish(string strEnglish)  
    2. {  
    3.     return "Hello." + strEnglish;  
    4. }  
    5.   
    6. Func<string, string> f = HelloEnglish;  
    7. Console.WriteLine(f("Srping ji"));  
    8. Console.ReadLine();  

C#中的Action<>和Func<>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.