委托与Lambda表达式

  

// 声明一个委托
// 委托就是一个类型
// Add: 委托类型的变量
// 类型: double(int, int)
//       是一个方法类型,返回值类型是double,参数类型是(int, int)
delegate double Add(int a, int b);


class Program {
    public static void Main(string[] args) {
        // 将Add类型的变量a指向Plus方法
        Add a = new Add(Plus);
        // 现在 a 就是 Plus 方法

        // 现在,将Plus和Minus方法都绑定给a,双重委托,a即表示Plus,又表示Minus方法
       //可以通过一次调用执行多个方法
        a += Minus;
        //打印最后一个方法的结果
        System.Console.WriteLine(a(10, 20));

    }
    public static double Plus(int a, int b) {
        System.Console.WriteLine("Plus");
        return a + b;
    }

    public static double Minus(int a, int b) {
        System.Console.WriteLine("Minus");
        return a - b;
    }
}

  

//Lambda表达式主要用于事件回调

using System;

// 委托
delegate int Method(int a, int b);
delegate string Method2(string s0, string s1);

class Program {
    public static void Main(string[] args) {
        Method m = Add;

        // 匿名函数(所谓的匿名,就是省略方法名)
        m = delegate (int x, int y) {
            return x + y;
        };

        // => 是Lambda运算符,读作 goes to
        // 是作为参数列表和方法体的分隔 
        m = (int x, int y) => {
            return x + y;
        };


        // 在上述Lambda表达式中,如果方法体中只有一句返回语句,那么可以这样简化
        m = (int x, int y) => x + y;

        // 上述式子还可以简化
        // int(int, int)
        m = (x, y) => x - y;

        // 上述式子,如果形参列表只有一个参数, 那么小括号可以不写
        Console.WriteLine(m(10, 20));   // ?


        Method2 m2 = (x, y) => x + y;
        m2("hello ", "world!");
    }

    public static int Add(int x, int y) {
        return x + y;
    }
}

  

原文地址:https://www.cnblogs.com/xingyunge/p/6829805.html