Lambda运算符(C#)

本文深入探讨了Lambda表达式在.NET中的应用,展示了其如何简化委托类型使用,通过实例对比传统语法、匿名方法及Lambda表达式的优劣,特别强调了在事件处理中的便捷性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Keep Learning

 

Lambda表达式只是用更简单的方式来写匿名方法,彻底简化对.NET委托类型的使用。

Lambda表达式可以简化为如下简单的形式:ArgumentsToProcess => StatementsToProcessThem

    public class Car {

        public delegate void AboutToBelow(string msg);

        private AboutToBelow almostDeadList;

        public void OnAboutToBelow(AboutToBelow clientMethod) {

            almostDeadList = clientMethod;

        }

        //...

}

    //传统的委托语法:

    static void test() {

        Car c = new Car("SlugBug", 100, 10);

        c.OnAboutToBelow(new Car.AboutToBelow(CarAboutToBelowClient));

    }

    public static void CarAboutToBelowClient(string msg) {

        Console.WriteLine(msg);

    }

    //使用匿名方法

    static void test() {

        Car c = new Car("SlugBug", 100, 10);

        c.OnAboutToBelow(delegate(string msg) { Console.WriteLine(msg); });

    }

    //使用Lambda表达式

    static void test() {

        Car c = new Car("SlugBug", 100, 10);

        c.OnAboutToBelow(msg => { Console.WriteLine(msg); });

}

 

//Lambda表达式和事件一起使用

    public class Car {

        public delegate void AboutToBelow(string msg);

        public event AboutToBelow AboutToBelowEvent;

        //...

    }

    static void test() {

        Car c = new Car("SlugBug", 100, 10);

        c.AboutToBelowEvent += (string msg)  =>  { Console.WriteLine(msg); };

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值