今天在看别人的代码时发现了这个——“=>”,看起来像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上讲解的也挺详细的,点这里传送。。