Lambda运算符(C#)

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); };

}

 

猜你喜欢

转载自blog.csdn.net/Nicky_1218/article/details/85161960