卷首語:匿名委託實指匿名方法或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文法差別還是挺大的……