[C#基礎]c#惡補之Lambda運算式

來源:互聯網
上載者:User

標籤:c#

今天在看別人的代碼時發現了這個——“=>”,看起來像c語言中的指標,又像是這個表情——":)",不管像什麼,確實把我難倒了,於是決定學習一下。


簡單地說,Lambda運算式就像是匿名委託。

using UnityEngine;using System.Collections;//若要建立 Lambda 運算式,需要在 Lambda 運算子 => 左側指定輸入參數(如果有),//然後在另一側輸入運算式或語句塊。//僅當 lambda 只有一個輸入參數時,括弧才是可選的;否則括弧是必需的。//括弧內的兩個或更多輸入參數使用逗號加以分隔public class TestCSharp : MonoBehaviour{    delegate void TestDelegate();    delegate void TestDelegate2(string s);    delegate void TestDelegate3(string m,string n);    delegate int TestDelegate4(int i);// Use this for initializationvoid Start ()     {        //=> 右側是語句塊,可以包含任意數量的語句        TestDelegate testDelA = () => { print("開始測試!"); print("準備好了嗎?"); };        TestDelegate2 testDelB = (x) => { print(x); };        TestDelegate3 testDelC = (x,y) => { print(x + y); };        testDelA();        testDelB("HelloWorld");        testDelC("世界","你好");        //=> 右側是運算式        TestDelegate4 testDelD = x => x * 11;        int j = testDelD(8); //j = 88        print(j);        //=> 右側是方法        TestDelegate testDelE = () => TestA();        testDelE();        TestDelegate testDelF = () => TestB();        testDelF += () => TestC();        testDelF();        TestD(() => TestB(), () => TestC());}    void TestA()    {        print("再見了!");    }    void TestB()    {        print("啊!");    }    void TestC()    {        print("我又回來了!");    }    void TestD(TestDelegate a,TestDelegate b)    {        a();        b();    } }


運行結果:


在TestD方法中,Lambda運算式直接當參數傳給了一個委託,你懂的。。

還有就是msdn上講解的也挺詳細的,點這裡傳送。。

[C#基礎]c#惡補之Lambda運算式

聯繫我們

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