標籤: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運算式