C#——Lambda

26 篇文章 1 订阅
本文介绍了C#中的Lambda表达式,包括不同版本的使用方式,从传统方法到使用箭头操作符的简洁形式。展示了Lambda如何与委托和Action、Func类型结合,以及在无返回值、带参数和带返回值情况下的应用。
摘要由CSDN通过智能技术生成

Lambda

namespace CSharpAdvancedLambda
{
    delegate void StudentDelegate(string name, int age);
    public class LambdaTest
    {
        public void Show()
        {
            DateTime dateTime = DateTime.Now;

            //历史
            //版本1(不可以访问局部变量)
            {
                StudentDelegate student = Student;
                student("Ant编程",1);
            }

            //版本2(优点:可以访问局部变量)
            {
                StudentDelegate student = new StudentDelegate(delegate (string name
                {
                    Console.Write(dateTime);
                    Console.WriteLine($"我的名字是{name},年龄是{age}");
                });
                student("Ant编程", 1);
            }

            //版本3( => 念gose to)
            {
                StudentDelegate student = new StudentDelegate((string name, int
                    age)=>
                {
                    Console.Write(dateTime);
                    Console.WriteLine($"我的名字是{name},年龄是{age}");
                });
                student("Ant编程", 1);
            }

            {
                //无返回值无参数
                Action action = () => Console.WriteLine("无返回值,无参数");
                action();

                //带参数的
                Action<DateTime> action1 = d => Console.WriteLine(d+"带一个参数"); 
                action1(DateTime.Now);

                //带返回值的
                Func<int,DateTime> func=(i)=>{ return DateTime.Now; };
                Console.WriteLine(func(5) + "带返回值");

                //简化
                Func<int, DateTime> func2 = (i) =>  DateTime.Now;
            }
        }

        public void Student(string name,int age)
        {
            Console.WriteLine($"我的名字是{name},年龄是{age}");
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值