这是 C# 2.0 时代的写法,现在很少用了。
delegate void Attack();
Attack a = delegate()
{
Console.WriteLine("偷袭!");
};
这是现在的江湖主流。左边是参数,右边是代码。
口诀:去 delegate,加箭头。
// 无参数
Action a = () => Console.WriteLine("偷袭!");
// 有参数 (x 是参数, => 后面是返回值)
Func square = x => x * x;
Console.WriteLine(square(5)); // 25
匿名方法厉害的地方在于,它可以捕获外面的变量!
int factor = 10;
Func multiplier = n => n * factor; // 它记住了外面的 factor
factor = 20; // 改了外面的变量
Console.WriteLine(multiplier(2)); // 输出 40!(2 * 20)
// 它用的是调用时的值,而不是定义时的值!
list.Where(x => x > 10).ToList(),一行代码就能筛选出大于10的元素,比写循环优雅一百倍!
创建一个整数列表 List<int> nums = { 1, 5, 10, 20, 3 };。
使用 Lambda 表达式和 FindAll 方法,找出所有大于 5 的数字,并打印出来。
List nums = new List { 1, 5, 10, 20, 3 };
List bigOnes = nums.FindAll(n => n > 5);
foreach (var n in bigOnes) Console.WriteLine(n);