C#匿名委託和匿名方法使用小技巧

來源:互聯網
上載者:User

  卷首語:匿名委託實指匿名方法或Lambda運算式。

  昨晚有一個朋友給我出了一個問題:

  在如下代碼中,怎樣才能輸出“Hello World”

1 if(---填入代碼---)
2{
3  Console.Write("Hello ");
4 }
5 else
6 {
7   Console.Write("World");
8 }

  當然,他說也可以用Java做,但是只能用一句話搞定。

  因為本人比較喜歡.NET這邊,所以首選C#試了一下。

  首先,我們很本能地想到,if-else語句塊中只能執行到一個(除了在特定情況下使用線程或者使用“true)else if(^!)^!”來截斷判斷等等非常規方法)。所以,我們理所當然地想到:必須在執行if條件時將Hello輸出。於是,我想到了匿名方法(註:參考http://baike.baidu.com/view/2308725.htm(匿名方法 百度百科)http://baike.baidu.com/view/2761370.htm(匿名委託 百度百科)http://msdn.microsoft.com/zh-cn/library/0yw3tz5k.aspx(匿名方法(C#編程指南)))。

  於是,我編寫了如下代碼:

 1 using System;
2
3 namespace HelloWorldOutPutTest1
4 {
5 // 定義委託
6 public delegate bool MyDelForTest1();
7
8 public class Test1
9 {
10 private MyDelForTest1 _test1; // 聲明委託變數
11
12 public static void Main(string[] args)
13 {
14 // 也可以使用如下寫法
15        // if (new Test1() { _test1 = delegate() { Console.Write("Hello "); return false; } }._test1())
16 if (new Test1() { _test1 = new MyDelForTest1(delegate() { Console.Write("Hello "); return false; } ) }._test1())
17 {
18 Console.Write("Hello ");
19 }
20 else
21 {
22 Console.Write("World");
23 }
24 }
25 }
26 }

  熟悉委託的朋友肯定對這種寫法不陌生,這種寫法是正確的,運用了匿名方法來實現,但是還是沒喲一句話解決啊!?

  後來那位朋友告訴我他的寫法:

 1 using System;
2
3 namespace HelloWorldOutPutTest2
4 {
5 public class Test2
6 {
7 public static void Main(string[] args)
8 {
9 if (new Func<bool>(() => { Console.Write("Hello "); return false; }).Invoke())
10 {
11 Console.Write("Hello ");
12 }
13 else
14 {
15 Console.Write("World");
16 }
17 }
18 }
19 }

  這下終於搞定了。使用了華麗的代碼(註:參考http://technet.microsoft.com/zh-cn/magazine/bb534960(VS.90).aspx(Func<(Of <(TResult>)>) 委託)http://technet.microsoft.com/zh-cn/magazine/bb397687(VS.90).aspx(Lambda 運算式(C# 編程指南)))。

  C#這邊OK了,Java如何呢?

  老師給了我們解決方案:

 1 package HelloWorldOutPutTest3;
2
3 public class Test3 {
4
5 public static void main(String[] args) {
6 if(new Test3(){ public boolean test() { System.out.print("Hello ");return false;} }.test()) {
7 System.out.print("Hello ");
8 }
9 else {
10 System.out.println("world");
11 }
12 }
13 }

  看來C#和Java文法差別還是挺大的……

聯繫我們

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