C#中Lambda表達(dá)式的三種寫法
更新時間:2022年05月05日 08:30:24 作者:農(nóng)碼一生
這篇文章介紹了C#中Lambda表達(dá)式的三種寫法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
一、歷史版本
delegate void StudentDelegate(string name, int age);
public class LambdaTest
{
public void Show()
{
DateTime dateTime = DateTime.Now;
//歷史
//版本1
{
StudentDelegate student = new StudentDelegate(PrintStudent);
student("葛優(yōu)", 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("無返回值,無參數(shù)");
Action<DateTime> action1 = d => { Console.WriteLine( $"帶一個參數(shù):ww64umi"); };
action1(dateTime);
Action<DateTime, int> action2 = (d, i) => { Console.WriteLine( $"帶兩個參數(shù):{ d} ,{ i}"); };
action2(dateTime, 3);
Func<DateTime> func=()=>{ return DateTime.Now; };//帶返回值
DateTime dateTime1 = func();//調(diào)用Lambda獲取值
Console.WriteLine(dateTime1);
Func<DateTime> func2 = () => DateTime.Now;//帶返回值
Console.WriteLine(func2());
}
}
}以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#窗體編程(windows forms)禁止窗口最大化的方法
這篇文章主要介紹了C#窗體編程(windows forms)禁止窗口最大化的方法,以及避免彈出系統(tǒng)菜單和禁止窗口拖拽的方法,需要的朋友可以參考下2014-08-08

