Lambda運算子(C#)
Keep Learning
Lambda表示式只是用更簡單的方式來寫匿名方法,徹底簡化對.NET委託型別的使用。
Lambda表示式可以簡化為如下簡單的形式:ArgumentsToProcess => StatementsToProcessThem
public class Car {
public delegate void AboutToBelow(string msg);
public void OnAboutToBelow(AboutToBelow clientMethod) {
almostDeadList = clientMethod;
}
}
//傳統的委託語法:
static void test() {
Car c = new Car("SlugBug", 100, 10);
c.OnAboutToBelow(new Car.AboutToBelow(CarAboutToBelowClient));
}
Console.WriteLine(msg);
}
//使用匿名方法
static void test() {
Car c = new Car("SlugBug", 100, 10);
c.OnAboutToBelow(delegate(string msg) { Console.WriteLine(msg); });
}
//使用Lambda表示式
static void test() {
Car c = new Car("SlugBug", 100, 10);
c.OnAboutToBelow(msg => { Console.WriteLine(msg); });
}
//Lambda表示式和事件一起使用
public class Car {
public delegate void AboutToBelow(string msg);
public event AboutToBelow AboutToBelowEvent;
//...
}
static void test() {
Car c = new Car("SlugBug", 100, 10);
c.AboutToBelowEvent += (string msg) => { Console.WriteLine(msg); };
}