今天在看別人的代碼時發現了這個——“=>”,看起來像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 initialization
void 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上講解的也挺詳細的,點這裡傳送。。