C#匿名方法與Delegate類型轉換錯誤

來源:互聯網
上載者:User

標籤:http   io   ar   os   使用   sp   on   問題   cti   

 問題描述  

       C#2.0出現了匿名方法, 這在一定程度上節省了我們維護代碼內容相關的精力, 也不需要思考為某個方法取什麼名字比較合適. 在FCL的一些方法中要求傳入一個Delegate類型的參數, 比如Control.Invoke或者Control.BeginInvoke方法:

0 public object Invoke(Delegate method); 

1 public IAsyncResult BeginInvoke(Delegate method);

        在這種情況下, 如果不使用匿名方法, 則需要在代碼的上面先聲明一個delegate void DoSomething()方法, 然後可以在Invoke方法中再用lambda運算式或者委託實現DoSomething().

0 delegate void DoSomething(); 

1   

2 private void App() 

3 { 

4     XXControl.Invoke(new DoSomething(() => 

5     { 

6         //DoSomething的具體操作 

7     })); 

8 }

        這樣做可以是可以, 但使用匿名方法則更好, 最起碼看上去更簡潔.

0 private void App() 

1 { 

2     XXControl.Invoke(delegate

3     { 

4         //DoSomething的具體操作 

5     }); 

6 }

        上面的代碼會在編譯的時候出錯: Cannot convert anonymous method to type System.Delegate because it is not a delegate type. 方法要求參數的是一個委託(delegate)類型, 而現在傳遞的只是一個匿名方法. 產生這個錯誤最根本的原因是編譯器在處理匿名方法的時候, 沒法推斷出這個委託的方法返回的是什麼類型, 也就不知道返回一個什麼樣的委託.

解決方案         要解決上面這個問題, 從根本上來說就是指定這個匿名方法將會返回什麼類型的委託, 有幾種方法:

        1. 使用MethodInvoke或者Action

0 private void App() 

1 { 

2     XXControl.Invoke((MethodInvoker)delegate() 

3     { 

4         //DoSomething的具體操作 

5     }); 

6 }  0 private void App() 

1 { 

2     XXControl.Invoke((Action)delegate() 

3     { 

4         //DoSomething的具體操作 

5     }); 

6 }

        MethodInvoke和Action都是方法傳回型別為空白的委託.

        2. 可以給Control定義一個Invoke的擴充方法

0 public static void Invoke(this Control control, Action action) 

1 { 

2     control.Invoke((Delegate)action); 

3 }

        調用的時候則可以這樣調用:

0 //使用委託 

1 XXControl.Invoke(delegate { //DoSomething  here}); 

2 //使用lambda運算式 

3 XXControl.Invoke(()=>{ //DoSomething here});

參考 1. http://stackoverflow.com/questions/253138/anonymous-method-in-invoke-call

2. http://staceyw1.wordpress.com/2007/12/22/they-are-anonymous-methods-not-anonymous-delegates/

 

C#匿名方法與Delegate類型轉換錯誤

聯繫我們

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