日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#中Lambda表達式的三種寫法_C#教程

作者:農碼一生 ? 更新時間: 2022-06-28 編程語言

一、歷史版本

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( $"帶一個參數:bsd5o550550j"); };
            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());
        }
    }
}

原文鏈接:https://www.cnblogs.com/wml-it/p/16078005.html

欄目分類
最近更新