C#使用Lambda表達(dá)式簡化代碼的示例詳解
Lambda,希臘字母λ,在C#編程語言中,被引入為Lambda表達(dá)式,表示為匿名函數(shù)(匿名方法)。
編程時(shí)離不開函數(shù),函數(shù)都有函數(shù)名和函數(shù)體,聲明函數(shù)名是為了方便多次使用,可是很多時(shí)候函數(shù)只使用一次,那么函數(shù)名就變得多余,這樣就產(chǎn)生了匿名函數(shù)(匿名方法)。
很多編程語言都有Lambde表達(dá)式,如Python、JavaScript、Java等等,這似乎是現(xiàn)代編程語言的標(biāo)配了。
作為編程語言C#和編程環(huán)境Visual Stuidio的發(fā)展,總得不停地變幻出新花樣,功能還是那個(gè)功能或者略有增強(qiáng),得益于編譯器的強(qiáng)大,C#3.0推出了Lambda表達(dá)式。
其實(shí)這些是非必要的,只是為C#編碼增加一些色彩和亮點(diǎn)而已,但是別人總喜歡這么寫,我們就得熟悉這些規(guī)則了。
舉例1:計(jì)算兩個(gè)整數(shù)的相加和相減。
① 一般寫法
//聲明變量 private delegate int calculate(int x, int y);//聲明一個(gè)用于計(jì)算的委托類型 private calculate MyCalculate;//聲明一個(gè)委托實(shí)例 //聲明函數(shù) private int Add(int x, int y) { return x+y; } private int Reduce(int x, int y) { return x - y; }
就可以直接使用了。
MyCalculate = new calculate(Add); string StrResultAdd = MyCalculate(7, 2).ToString(); MyCalculate = new calculate(Reduce); string StrResultReduce = MyCalculate(7, 2).ToString(); // textBox1.Text = $"兩數(shù)相加結(jié)果:{StrResultAdd}" + Environment.NewLine; textBox1.Text = textBox1.Text+ $"兩數(shù)相減結(jié)果:{StrResultReduce}" + Environment.NewLine;
② 使用自定義的委托
使用自定義的委托來使用Lamda可以讓代碼更簡潔:
MyCalculate = delegate(int x,int y) { return x + y; }; textBox1.Text = textBox1.Text+"兩數(shù)相加結(jié)果:" + MyCalculate(7, 2).ToString()+Environment.NewLine; MyCalculate = delegate (int x, int y) { return x - y; }; textBox1.Text = textBox1.Text + "兩數(shù)相減結(jié)果:" + MyCalculate(7, 2).ToString() + Environment.NewLine;
上面得到的結(jié)果是一樣的。
③ 使用Func委托
FUNC委托的重載:
Func<TResult>;
Func<T1,T2,TResult>;
Func<T1,...,T16,TResult>;
使用系統(tǒng)內(nèi)置的FUNC命名的委托來寫LambDa表達(dá)式:
Func<int,int,int> MyAdd = (int x, int y) => { return x + y; }; Func<int, int, int> MyReduce = (int x, int y) => { return x - y; }; textBox1.Text = textBox1.Text + $"兩數(shù)相加結(jié)果:{MyAdd(7,2).ToString()}" + Environment.NewLine; textBox1.Text = textBox1.Text + $"兩數(shù)相減結(jié)果:{MyReduce(7, 2).ToString()}" + Environment.NewLine;
④ 使用規(guī)范的Lambda表達(dá)式
更簡潔的寫法:
MyCalculate = (int x, int y) => { return x + y; }; textBox1.Text = textBox1.Text+$"兩數(shù)相加結(jié)果:{MyCalculate(7, 2).ToString()}" + Environment.NewLine; MyCalculate = (int x, int y) => { return x - y; }; textBox1.Text = textBox1.Text+$"兩數(shù)相減結(jié)果:{MyCalculate(7, 2).ToString()}" + Environment.NewLine;
完整代碼:
namespace Lambda { public partial class Form1 : Form { private delegate int calculate(int x, int y);//聲明一個(gè)用于計(jì)算的委托類型 private calculate MyCalculate;//聲明一個(gè)委托實(shí)例 public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //1 MyCalculate = new calculate(Add); string StrResultAdd = MyCalculate(7, 2).ToString(); MyCalculate = new calculate(Reduce); string StrResultReduce = MyCalculate(7, 2).ToString(); textBox1.Text = $"兩數(shù)相加結(jié)果:{StrResultAdd}" + Environment.NewLine; textBox1.Text = textBox1.Text+ $"兩數(shù)相減結(jié)果:{StrResultReduce}" + Environment.NewLine; //2 MyCalculate = delegate(int x,int y) { return x + y; }; textBox1.Text = textBox1.Text+"兩數(shù)相加結(jié)果:" + MyCalculate(7, 2).ToString()+Environment.NewLine; MyCalculate = delegate (int x, int y) { return x - y; }; textBox1.Text = textBox1.Text + "兩數(shù)相減結(jié)果:" + MyCalculate(7, 2).ToString() + Environment.NewLine; //3 Func<int,int,int> MyAdd = (int x, int y) => { return x + y; }; Func<int, int, int> MyReduce = (int x, int y) => { return x - y; }; textBox1.Text = textBox1.Text + $"兩數(shù)相加結(jié)果:{MyAdd(7,2).ToString()}" + Environment.NewLine; textBox1.Text = textBox1.Text + $"兩數(shù)相減結(jié)果:{MyReduce(7, 2).ToString()}" + Environment.NewLine; //4 MyCalculate = (int x, int y) => { return x + y; }; textBox1.Text = textBox1.Text+$"兩數(shù)相加結(jié)果:{MyCalculate(7, 2).ToString()}" + Environment.NewLine; MyCalculate = (int x, int y) => { return x - y; }; textBox1.Text = textBox1.Text+$"兩數(shù)相減結(jié)果:{MyCalculate(7, 2).ToString()}" + Environment.NewLine; } private int Add(int x, int y) { return x+y; } private int Reduce(int x, int y) { return x - y; }
結(jié)果顯示:
上面通過對比說明了Lambda表達(dá)式的應(yīng)用,可以看出這樣的寫法相比傳統(tǒng)的寫法還是干凈利落,的確簡潔而優(yōu)雅一些。
上面的可以改寫:
private delegate int calculate1(int x, int y,string str);//聲明一個(gè)用于計(jì)算的委托類型 private calculate1 MyCalculate1;//聲明一個(gè)委托實(shí)例 MyCalculate1 = (int x, int y,string StrOP) => { switch (StrOP) { case "+": return x + y; break; case "-": return x - y; break; default: return 0; break; } }; textBox1.Text = textBox1.Text + $"兩數(shù)相加結(jié)果:{MyCalculate1(7, 2,"+").ToString()}" + Environment.NewLine; textBox1.Text = textBox1.Text + $"兩數(shù)相減結(jié)果:{MyCalculate1(7, 2,"-").ToString()}" + Environment.NewLine;
或者:
Func<int, int, string,int> MyOperate = (int x, int y, string StrOP) => { switch (StrOP) { case "+": return x + y; break; case "-": return x - y; break; default: return 0;break; } }; textBox1.Text = textBox1.Text + $"兩數(shù)相加結(jié)果:{MyOperate(7, 2,"+").ToString()}" + Environment.NewLine; textBox1.Text = textBox1.Text + $"兩數(shù)相減結(jié)果:{MyOperate(7, 2,"-").ToString()}" + Environment.NewLine;
從上面的代碼演示中可以看出,Lambda與委托是緊密相連的。
舉例2:求幾個(gè)數(shù)的最大值與最小值。
① 一般寫法:
private void button2_Click(object sender, EventArgs e) { textBox1.Text += "最大值:"+GetMax(new int[6]{7, 11,23,4,15,6}).ToString(); textBox1.Text += Environment.NewLine; textBox1.Text += "最小值:" + GetMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString(); } private static int GetMax(int[] Arr) { int ReturnValue = Arr[0]; foreach( int a in Arr) { if(a > ReturnValue) ReturnValue = a; } return ReturnValue; } private static int GetMin(int[] Arr) { int ReturnValue = Arr[0]; foreach (int a in Arr) { if (a < ReturnValue) ReturnValue = a; } return ReturnValue; }
② 使用委托來改寫:
//聲明委托 private delegate int GetMaxOrMin(int[] Arr); private GetMaxOrMin MyGetMaxOrMin; //定義函數(shù) private static int GetMax(int[] Arr) { int ReturnValue = Arr[0]; foreach( int a in Arr) { if(a > ReturnValue) ReturnValue = a; } return ReturnValue; } private static int GetMin(int[] Arr) { int ReturnValue = Arr[0]; foreach (int a in Arr) { if (a < ReturnValue) ReturnValue = a; } return ReturnValue; } //使用 private void button2_Click(object sender, EventArgs e) { MyGetMaxOrMin = new GetMaxOrMin( GetMax); textBox1.Text += "最大值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString(); textBox1.Text += Environment.NewLine; MyGetMaxOrMin = new GetMaxOrMin(GetMin); textBox1.Text += "最小值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString(); }
③ 使用自定義的委托
MyGetMaxOrMin=delegate(int[] Arr) { int ReturnValue = Arr[0]; foreach (int a in Arr) { if (a > ReturnValue) ReturnValue = a; } return ReturnValue; }; textBox1.Text += "最大值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString(); MyGetMaxOrMin = delegate (int[] Arr) { int ReturnValue = Arr[0]; foreach (int a in Arr) { if (a < ReturnValue) ReturnValue = a; } return ReturnValue; }; textBox1.Text += "最小值:" + GetMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
到這里,我們看到這兩個(gè)方法只是判斷位置的代碼略有不同,其他的都相同,那么這個(gè)地方就可以使用委托來代替,就是把判斷方法當(dāng)做參數(shù)傳進(jìn)去。
private delegate Boolean Judge(int x,int y);//定義判斷 private Judge MyJudge;//實(shí)例化委托 private delegate int GetMaxOrMin(int[] Arr,Judge j);//定義得到最大值或者最小值的計(jì)算方法 private GetMaxOrMin MyGetMaxOrMin;//實(shí)例化 private void button2_Click(object sender, EventArgs e) { MyGetMaxOrMin=delegate(int[] Arr,Judge MyJude) { int ReturnValue = Arr[0]; foreach (int a in Arr) { if (MyJudge(a,ReturnValue)) ReturnValue = a; } return ReturnValue; }; MyJudge = delegate (int x, int y) { return x > y; }; textBox1.Text += "最大值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 },MyJudge).ToString(); MyJudge = delegate (int x, int y) { return x < y; }; textBox1.Text += "最小值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 },MyJudge).ToString(); }
上面的寫法的效果是一樣的。
④ 使用Func委托
Func<int[],Judge,int> MyGetMax = (int[] Arr,Judge MyJudge) => { int ReturnValue = Arr[0]; foreach (int a in Arr) { if (MyJudge(a, ReturnValue)) ReturnValue = a; } return ReturnValue; }; MyJudge = delegate (int x, int y) { return x > y; }; textBox1.Text += "最大值:" + MyGetMax(new int[6] { 7, 11, 23, 4, 15, 6 },MyJudge).ToString(); MyJudge = delegate (int x, int y) { return x < y; }; textBox1.Text += "最小值:" + MyGetMax(new int[6] { 7, 11, 23, 4, 15, 6 }, MyJudge).ToString();
⑤ 使用更簡潔的Lambda表達(dá)式
var MyGetMaxOrMin1 = (int[] Arr,Judge J1 ) => { int ReturnValue = Arr[0]; foreach (int a in Arr) { if (J1(a, ReturnValue)) ReturnValue = a; } return ReturnValue; }; Judge JudgeMax = (int x, int y) => { return x > y; }; textBox1.Text += "最大值:" + MyGetMaxOrMin1(new int[6] { 7, 11, 23, 4, 15, 6 }, JudgeMax).ToString(); Judge JudgeMin = (int x, int y) => { return x < y; }; textBox1.Text += "最小值:" + MyGetMaxOrMin1(new int[6] { 7, 11, 23, 4, 15, 6 }, JudgeMin).ToString();
完整代碼:
using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Security.Cryptography.X509Certificates; namespace Lambda { public partial class Form1 : Form { private delegate int calculate(int x, int y);//聲明一個(gè)用于計(jì)算的委托類型 private calculate MyCalculate;//聲明一個(gè)委托實(shí)例 private delegate int calculate1(int x, int y,string str);//聲明一個(gè)用于計(jì)算的委托類型 private calculate1 MyCalculate1;//聲明一個(gè)委托實(shí)例 private delegate Boolean Judge(int x,int y); private Judge MyJudge; private delegate int GetMaxOrMinA(int[] Arr); private GetMaxOrMinA MyGetMaxOrMinA; private delegate int GetMaxOrMin(int[] Arr,Judge j); private GetMaxOrMin MyGetMaxOrMin; public Form1() { InitializeComponent(); } private void button2_Click(object sender, EventArgs e) { textBox1.Text += "最大值:" + GetMax(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString(); textBox1.Text += "最小值:" + GetMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString(); textBox1.Text += Environment.NewLine +"=====" + Environment.NewLine; MyGetMaxOrMinA = new GetMaxOrMinA(GetMax); textBox1.Text += "最大值:" + MyGetMaxOrMinA(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString(); MyGetMaxOrMinA = new GetMaxOrMinA(GetMin); textBox1.Text += "最小值:" + MyGetMaxOrMinA(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString(); textBox1.Text += Environment.NewLine + "=====" + Environment.NewLine; MyGetMaxOrMin = delegate (int[] Arr, Judge MyJude) { int ReturnValue = Arr[0]; foreach (int a in Arr) { if (MyJudge(a, ReturnValue)) ReturnValue = a; } return ReturnValue; }; MyJudge = delegate (int x, int y) { return x > y; }; textBox1.Text += "最大值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 }, MyJudge).ToString(); MyJudge = delegate (int x, int y) { return x < y; }; textBox1.Text += "最小值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 }, MyJudge).ToString(); textBox1.Text += Environment.NewLine +"=====" + Environment.NewLine; Func<int[], Judge, int> MyGetMax = (int[] Arr, Judge MyJudge) => { int ReturnValue = Arr[0]; foreach (int a in Arr) { if (MyJudge(a, ReturnValue)) ReturnValue = a; } return ReturnValue; }; MyJudge = delegate (int x, int y) { return x > y; }; textBox1.Text += "最大值:" + MyGetMax(new int[6] { 7, 11, 23, 4, 15, 6 }, MyJudge).ToString(); MyJudge = delegate (int x, int y) { return x < y; }; textBox1.Text += "最小值:" + MyGetMax(new int[6] { 7, 11, 23, 4, 15, 6 }, MyJudge).ToString(); textBox1.Text += Environment.NewLine +"=====" + Environment.NewLine; var MyGetMaxOrMin1 = (int[] Arr,Judge Judge1 ) => { int ReturnValue = Arr[0]; foreach (int a in Arr) { if (Judge1(a, ReturnValue)) ReturnValue = a; } return ReturnValue; }; Judge JudgeMax = (int x, int y) => { return x > y; }; textBox1.Text += "最大值:" + MyGetMaxOrMin1(new int[6] { 7, 11, 23, 4, 15, 6 }, JudgeMax).ToString(); Judge JudgeMin = (int x, int y) => { return x < y; }; textBox1.Text += "最小值:" + MyGetMaxOrMin1(new int[6] { 7, 11, 23, 4, 15, 6 }, JudgeMin).ToString(); } private static int GetMax(int[] Arr) { int ReturnValue = Arr[0]; foreach( int a in Arr) { if(a > ReturnValue) ReturnValue = a; } return ReturnValue; } private static int GetMin(int[] Arr) { int ReturnValue = Arr[0]; foreach (int a in Arr) { if (a < ReturnValue) ReturnValue = a; } return ReturnValue; } private static List<int> GetEven(List<int> list) { List<int> ReturnList =new List<int>(); foreach (var a in list) { if (a %2 == 0) ReturnList.Add(a); } return ReturnList; } private static List<int> GetOdd(List<int> list) { List<int> ReturnList = new List<int>(); foreach (var a in list) { if ( (a+1) % 2 == 0) ReturnList.Add(a); } return ReturnList; } } }
顯示結(jié)果圖:
到此這篇關(guān)于C#使用Lambda表達(dá)式簡化代碼的示例詳解的文章就介紹到這了,更多相關(guān)C# Lambda表達(dá)式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C# StreamReader類實(shí)現(xiàn)讀取文件的方法
這篇文章主要介紹了C# StreamReader類實(shí)現(xiàn)讀取文件的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01C#?wpf?Bitmap轉(zhuǎn)換成WriteableBitmap的方法
本文主要介紹了C#?wpf?Bitmap轉(zhuǎn)換成WriteableBitmap的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08C#實(shí)現(xiàn)將商品金額小寫轉(zhuǎn)換成大寫的方法
這篇文章主要介紹了C#實(shí)現(xiàn)將商品金額小寫轉(zhuǎn)換成大寫的方法,涉及C#數(shù)組與字符串的相關(guān)操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2016-08-08C#后端接收form-data,創(chuàng)建實(shí)體類教程
這篇文章主要介紹了C#后端接收form-data,創(chuàng)建實(shí)體類教程,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06基于數(shù)據(jù)類型轉(zhuǎn)換(裝箱與拆箱)與常量詳解
下面小編就為大家分享一篇基于數(shù)據(jù)類型轉(zhuǎn)換(裝箱與拆箱)與常量詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-11-11C#控制臺程序的開發(fā)與打包為一個(gè)exe文件實(shí)例詳解
所謂控制臺程序,就是沒有界面,運(yùn)行程序后只有一個(gè)黑色的類似cmd窗口,通過這個(gè)窗口進(jìn)行交互,下面這篇文章主要給大家介紹了關(guān)于C#控制臺程序的開發(fā)與打包為一個(gè)exe文件的相關(guān)資料,需要的朋友可以參考下2023-05-05