一、历史版本 delegate void StudentDelegate(string name, int age); public class LambdaTest { p
delegate void StudentDelegate(string name, int age);
public class LambdaTest
{
public void Show()
{
DateTime dateTime = DateTime.Now;
//历史
//版本1
{
StudentDelegate student = new StudentDelegate(PrintStudent);
student("葛优", 1);
}
}
}
public void PrintStudent(string name,int age)
{
Console.WriteLine($"我的名字是:{name},我的年龄是{age}");
}
delegate void StudentDelegate(string name, int age);
public class LambdaTest
{
public void Show()
{
DateTime dateTime = DateTime.Now;
//版本2(这样写的话可以访问局部变量)
{
StudentDelegate student = new StudentDelegate( delegate (string name, int age)
{
Console.Write(dateTime);
Console.WriteLine($"我的名字是:{name},我的年龄是{age}");
});
student("王朝伟", 1);
}
}
}
delegate void StudentDelegate(string name, int age);
public class LambdaTest
{
public void Show()
{
DateTime dateTime = DateTime.Now;
//版本3(=>念成Gose to)
{
StudentDelegate student = new StudentDelegate((string name, int age)=>
{
Console.Write(dateTime);
Console.WriteLine($"我的名字是:{name},我的年龄是{age}");
});
student("刘德华", 1);
}
{
Action action = () => Console.WriteLine("无返回值,无参数");
Action<DateTime> action1 = d => { Console.WriteLine( $"带一个参数:{d}"); };
action1(dateTime);
Action<DateTime, int> action2 = (d, i) => { Console.WriteLine( $"带两个参数:{ d} ,{ i}"); };
action2(dateTime, 3);
Func<DateTime> func=()=>{ return DateTime.Now; };//带返回值
DateTime dateTime1 = func();//调用Lambda获取值
Console.WriteLine(dateTime1);
Func<DateTime> func2 = () => DateTime.Now;//带返回值
Console.WriteLine(func2());
}
}
}
--结束END--
本文标题: C#中Lambda表达式的三种写法
本文链接: https://www.lsjlt.com/news/147891.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0