c#委托及lambda表达式

  委托也可以看作一种数据类型,可以定义变量,但是它是一种特殊的变量。

  委托定义的变量能接收的数值只能是一个方法(函数),可以理解成委托叫是一个方法(函数)的指针。

namespace delegate1
{
    class Program
    {
        static void Main(string[] args)
        {
            //(3)创建委托对象,关联具体方法
            CalculatorDelegate objCal = new CalculatorDelegate(Add);
            //(4)通过委托调用方法,而不是直接使用方法
            int result = objCal(10, 20);
            Console.WriteLine(result);
            objCal -= Add;  //将委托变量代表的具体方法解绑。
            objCal += Sub;
            result = objCal(10, 20);
            Console.WriteLine(result);
            Console.ReadLine();
        }
        //(2)根据委托定义一个“具体方法”实现加法功能
        static int Add(int a,int b)
        {
            return a + b;
        }
        //(2)根据委托定义一个“具体方法”实现减法功能
        static int Sub(int a,int b)
        {
            return a - b;
        }
    }
    //(1)声明委托(定义一个函数的原型:返回值:参数类型和个数)
    public delegate int CalculatorDelegate(int a, int b);
}

 

 

  lambda表达式:就是方法的简写。

  Delegate delegate=()=>{};

  其中()内的是参数,{}内的是方法体。

  1)有返回值有参数:

  public delegate int WithReturnWithPara(int a,int b);

  表达式:

  WithReturnWithPara withReturnWithPara=(a,b)=>{return a+b;};

  简化:去掉大括号和return,变为:

  WithReturnWithPara withReturnWithPara = (a,b) => a + b;

  2)无参数无返回值:

  public delegate void NoParaNoReturn();

  表达式:

  NoParaNoReturn noParaNoReturn = () =>{};

  NoParaNoReturn noParaNoReturn = () =>Console.WriteLine(1111);

  3)有参数无返回值:

  public delegate void WithParaNoReturn(string name,int id);

  表达式:

   WithParaNoReturn method2 = (name,id) => { Console.WriteLine("aaaa,{0},{1}", name, id); };

  4)无参数有返回值:

  public delegate int NoParaWithReturn();

  表达式:

  NoParaWithReturn noParaWithReturn =() => 1;

  泛型委托:

  (1)无参数无返回值:

  Action act1=()=>{};

  (2)多个参数无返回值(最多可以有16个参数):

    Action <string,int>act2=(s,i)=>{};  //只有一个参数可以省略小括号:

    Action <string>act2 = s => {};

  (3)无参数带返回值:

    Func<string> fun1=()=>"aaaa";

  (4)有参数有返回值:<>中最后一个是返回值,前面的都是参数。

    Func<string,int>func2=(string)=>1;

 

posted @ 2018-11-24 15:28  牛牛11  阅读(1634)  评论(0编辑  收藏  举报