Lambda
namespace CSharpAdvancedLambda
{
delegate void StudentDelegate(string name, int age);
public class LambdaTest
{
public void Show()
{
DateTime dateTime = DateTime.Now;
//历史
//版本1(不可以访问局部变量)
{
StudentDelegate student = Student;
student("Ant编程",1);
}
//版本2(优点:可以访问局部变量)
{
StudentDelegate student = new StudentDelegate(delegate (string name
{
Console.Write(dateTime);
Console.WriteLine($"我的名字是{name},年龄是{age}");
});
student("Ant编程", 1);
}
//版本3( => 念gose to)
{
StudentDelegate student = new StudentDelegate((string name, int
age)=>
{
Console.Write(dateTime);
Console.WriteLine($"我的名字是{name},年龄是{age}");
});
student("Ant编程", 1);
}
{
//无返回值无参数
Action action = () => Console.WriteLine("无返回值,无参数");
action();
//带参数的
Action<DateTime> action1 = d => Console.WriteLine(d+"带一个参数");
action1(DateTime.Now);
//带返回值的
Func<int,DateTime> func=(i)=>{ return DateTime.Now; };
Console.WriteLine(func(5) + "带返回值");
//简化
Func<int, DateTime> func2 = (i) => DateTime.Now;
}
}
public void Student(string name,int age)
{
Console.WriteLine($"我的名字是{name},年龄是{age}");
}
}
}

本文介绍了C#中的Lambda表达式,包括不同版本的使用方式,从传统方法到使用箭头操作符的简洁形式。展示了Lambda如何与委托和Action、Func类型结合,以及在无返回值、带参数和带返回值情况下的应用。
1663

被折叠的 条评论
为什么被折叠?



