最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#使用Lambda表達(dá)式簡化代碼的示例詳解

 更新時間:2022年12月02日 08:38:30   作者:dawn  
Lambda,希臘字母λ,在C#編程語言中,被引入為Lambda表達(dá)式,表示為匿名函數(shù)(匿名方法)。本文將利用Lambda表達(dá)式進(jìn)行代碼的簡化,感興趣的可以了解一下

Lambda,希臘字母λ,在C#編程語言中,被引入為Lambda表達(dá)式,表示為匿名函數(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ā)展,總得不停地變幻出新花樣,功能還是那個功能或者略有增強(qiáng),得益于編譯器的強(qiáng)大,C#3.0推出了Lambda表達(dá)式。

其實(shí)這些是非必要的,只是為C#編碼增加一些色彩和亮點(diǎn)而已,但是別人總喜歡這么寫,我們就得熟悉這些規(guī)則了。

舉例1:計(jì)算兩個整數(shù)的相加和相減。

①  一般寫法

        //聲明變量
        private delegate int calculate(int x, int y);//聲明一個用于計(jì)算的委托類型
        private calculate MyCalculate;//聲明一個委托實(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);//聲明一個用于計(jì)算的委托類型
        private calculate MyCalculate;//聲明一個委托實(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);//聲明一個用于計(jì)算的委托類型
        private calculate1 MyCalculate1;//聲明一個委托實(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:求幾個數(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();

到這里,我們看到這兩個方法只是判斷位置的代碼略有不同,其他的都相同,那么這個地方就可以使用委托來代替,就是把判斷方法當(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);//聲明一個用于計(jì)算的委托類型
        private calculate MyCalculate;//聲明一個委托實(shí)例
 
        private delegate int calculate1(int x, int y,string str);//聲明一個用于計(jì)算的委托類型
        private calculate1 MyCalculate1;//聲明一個委托實(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#中的并發(fā)編程與.NET任務(wù)并行庫的使用示例和常見問題

    C#中的并發(fā)編程與.NET任務(wù)并行庫的使用示例和常見問題

    在現(xiàn)代軟件開發(fā)中,.NET Framework通過引入任務(wù)并行庫(TPL)和并發(fā)集合類型,簡化了并發(fā)復(fù)雜性,提高程序的性能、可維護(hù)性和可擴(kuò)展性,并發(fā)集合設(shè)計(jì)上允許多線程安全訪問,此外,TPL通過Task類簡化異步操作,正確使用這些工具可避免死鎖和競爭條件等常見問題
    2024-09-09
  • C#從實(shí)體對象集合中導(dǎo)出Excel的代碼

    C#從實(shí)體對象集合中導(dǎo)出Excel的代碼

    數(shù)據(jù)的導(dǎo)出是項(xiàng)目中經(jīng)常要實(shí)現(xiàn)的功能,就拿最常見的要導(dǎo)出成Excel來說,網(wǎng)上看來看去,都是介紹從Datatable中導(dǎo)出
    2008-08-08
  • unity實(shí)現(xiàn)場景跳轉(zhuǎn)

    unity實(shí)現(xiàn)場景跳轉(zhuǎn)

    這篇文章主要為大家詳細(xì)介紹了unity實(shí)現(xiàn)場景跳轉(zhuǎn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-04-04
  • C# 面向?qū)ο蟮幕驹瓌t

    C# 面向?qū)ο蟮幕驹瓌t

    什么是面向?qū)ο蟮幕驹瓌t?設(shè)計(jì)原則是基本的工具,應(yīng)用這些規(guī)則可以使你的代碼更加靈活、更容易維護(hù),更容易擴(kuò)展。
    2009-11-11
  • C#獲取進(jìn)程或線程相關(guān)信息的方法

    C#獲取進(jìn)程或線程相關(guān)信息的方法

    這篇文章主要介紹了C#獲取進(jìn)程或線程相關(guān)信息的方法,涉及C#操作進(jìn)程及線程的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-08-08
  • C#中使用ADOMD.NET查詢多維數(shù)據(jù)集的實(shí)現(xiàn)方法

    C#中使用ADOMD.NET查詢多維數(shù)據(jù)集的實(shí)現(xiàn)方法

    這篇文章主要介紹了C#中使用ADOMD.NET查詢多維數(shù)據(jù)集的實(shí)現(xiàn)方法,詳細(xì)講述了C#中使用ADOMD.NET查詢多維數(shù)據(jù)集的原理與實(shí)現(xiàn)技巧,需要的朋友可以參考下
    2014-10-10
  • C#獲取文件夾及文件的大小與占用空間的方法

    C#獲取文件夾及文件的大小與占用空間的方法

    這篇文章主要介紹了C#獲取文件夾及文件的大小與占用空間的方法,需要的朋友可以參考下
    2014-07-07
  • C#多線程中的互斥鎖Mutex

    C#多線程中的互斥鎖Mutex

    這篇文章介紹了C#多線程中的互斥鎖Mutex,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-04-04
  • C# WinForm程序設(shè)計(jì)簡單計(jì)算器

    C# WinForm程序設(shè)計(jì)簡單計(jì)算器

    這篇文章主要為大家詳細(xì)介紹了C# WinForm程序設(shè)計(jì)簡單計(jì)算器,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-02-02
  • C# WebApi 接口返回值不困惑:返回值類型詳解

    C# WebApi 接口返回值不困惑:返回值類型詳解

    這篇文章主要介紹了C# WebApi 接口返回值不困惑:返回值類型詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-07-07

最新評論

韶山市| 津南区| 杭锦后旗| 岚皋县| 独山县| 长顺县| 屏边| 日喀则市| 邯郸市| 水城县| 广平县| 赤壁市| 四平市| 蒲城县| 辉南县| 礼泉县| 大关县| 图们市| 临夏市| 东山县| 江陵县| 理塘县| 新兴县| 梅州市| 改则县| 容城县| 库车县| 石门县| 乾安县| 石泉县| 海阳市| 榆树市| 荣昌县| 雷州市| 吴桥县| 高清| 尖扎县| 青海省| 武威市| 修文县| 溆浦县|