这篇文章介绍了C#中Lambda表达式的三种写法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
一、历史版本
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());
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持得得之家。
沃梦达教程
本文标题为:C#中Lambda表达式的三种写法
猜你喜欢
- 如何使用C# 捕获进程输出 2023-03-10
- c# 模拟线性回归的示例 2023-03-14
- Oracle中for循环的使用方法 2023-07-04
- WPF使用DrawingContext实现绘制刻度条 2023-07-04
- Unity Shader实现模糊效果 2023-04-27
- user32.dll 函数说明小结 2022-12-26
- C# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16
- 在C# 8中如何使用默认接口方法详解 2023-03-29
- Unity3D实现渐变颜色效果 2023-01-16
- .NET CORE DI 依赖注入 2023-09-27