lambda運算式與函數指標

來源:互聯網
上載者:User

猜猜下面兩部分C#代碼的輸出是什麼:

 (一)

        static void Main(string[] args)
        {
            Print(23);
            Console.ReadKey();
        }
        static Action Print(int n)
        {
            return () =>
                      {
                          Console.WriteLine(n);                 
                      };
        }

 

(二)

        static void Main(string[] args)
        {
            Print()(23);
            Console.ReadKey();
        }
        static Action<int> Print()
        {
            return (int n) =>
                      {
                          Console.WriteLine(n);                 
                      };
        }

 

如果你是一個C++程式員, 也許上面並不是個陌生的用法, 因為C++裡面可以使用函數指標,如下:

#include <iostream> 
using namespace std; 

void Print(int a); 

int main()    

    typedef void (*Action)(int a);//定義一個名為Action的函數指標類型,C#中的委託類似. 
    Action action=Print;
    (*action)(23);//注意這裡與(二)中的用法是類似的。
    getchar();
    return 0;


void Print(int a) 

    cout<<a<<endl; 
}

 

但是C#裡面沒有, 不過C#裡面有委託. 它起著類似的作用, Lambda運算式的值是委託類型, 第一個例子裡面什麼輸出也沒有, Print函數簡單返回了一個委託(Action類型), 也可以看作是指向函數Funtion(){Console.WriteLine(n);}的函數指標.但是函數本身並沒有在這裡得到執行。如果你看了第二個例子你也許會更清楚這一點,第二個例子用一句話說就是調用了該Action<int>指向的那個函數。

不過即便是第二種寫法,我還是不建議使用,因為它不易閱讀,不夠“優雅”。

 

 

聯繫我們

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