Keep Learning
Lambda表达式只是用更简单的方式来写匿名方法,彻底简化对.NET委托类型的使用。
Lambda表达式可以简化为如下简单的形式:ArgumentsToProcess => StatementsToProcessThem
public class Car {
public delegate void AboutToBelow(string msg);
private AboutToBelow almostDeadList;
public void OnAboutToBelow(AboutToBelow clientMethod) {
almostDeadList = clientMethod;
}
//...
}
//传统的委托语法:
static void test() {
Car c = new Car(\"SlugBug\", 100, 10);
c.OnAboutToBelow(new Car.AboutToBelow(CarAboutToBelowClient));
}
public static void CarAboutToBelowClient(string msg) {
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); };
}
继续阅读与本文标签相同的文章
-
第六届世界互联网大会“新看点”大盘点
2026-05-14栏目: 教程
-
特斯拉自动驾驶系统涨价遭质疑 马斯克:我们不能一直亏钱
2026-05-14栏目: 教程
-
首个二类资源区平价光伏电站正式并网发电
2026-05-14栏目: 教程
-
AI+5G科技创新 视频行业呈现轻应用化趋势
2026-05-14栏目: 教程
-
1.98亿滴滴用户添加了紧急联系人 每天百万个订单行程分享给亲友
2026-05-14栏目: 教程
