CSharp的lambda表达式的使用

发布时间 2023-07-03 20:03:57作者: 流浪のwolf
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

// 命名空间
namespace pro01
{
    //
    internal class Program
    {
        // main 方法
        static async Task Main(string[] args)
        {
            // Action 没有返回值
            Console.WriteLine("委托");
            Action f1 = delegate () {
                Console.WriteLine("我是无参的委托!!");
            };
            f1();
            Action<string ,int> f2 = delegate (string name, int i)
            {
                Console.WriteLine($"我是有参的委托 参数是 {name}{i}");
            };
            f2("参数o",100);
            // 带返回值的 Func  ps: Func 的泛型<> 要比()形参的个数多一个 因为多了一个返回值的类型
            // 最后一个泛型就是返回值
            // 匿名函数就是函数表达式 就是 箭头函数
            Func<int,int,int,string> fn3 = delegate (int i,int j,int z)
            {
                return (i + j + z).ToString();
            };
            Console.WriteLine(fn3(1,2,3));  // 6

            // 改装成箭头函数(lambada表达式) 新参的类型可以褪去 因为可以推断
            Func<string, string> fn4 = (name) =>
            {
                Console.WriteLine($"这里是匿名函数{name}");
                return name;
            };
            Console.WriteLine(fn4("lambda表达式"));

            // 没有返回值的 而且 只有一行代码 时候可以不写 {} 
            Action fn5 = () => Console.WriteLine("省咯大括号");
            fn5();







            Console.ReadLine();
        }

    }
}