这篇文章介绍了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#中的Linq to JSON操作详解 2023-06-08
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- Unity shader实现高斯模糊效果 2023-01-16
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C# 解析XML和反序列化的示例 2023-04-14