c# lambda表达式推演

//lambda表达式是什么? 左边是参数列表 goes to语法 右边是方法体,本质就是一个方法
//      lambda不是委托,因为委托是一个类型
//      也不是委托的实例,因为这里省略了 new 委托()
//      他的作用:是一个方法
//         编译后:lambda 实际上会生成一个类中类里面的一个internal修饰的方法,然后被绑定到静态的委托类型的字段    

    //声明委托:不带参
    private delegate void DelegateMethod();
    //声明委托:带参   
    private delegate void DelegateMethod2(int x, int y);
     public void Test()
        {
            //1.0  1.1
            DelegateMethod method = new DelegateMethod(CallMethod);

            //2.0 匿名方法      拷贝callMethod方法块,把 private void callMethod 换成 delegate
            DelegateMethod method2 = new DelegateMethod(delegate()
            {
                Console.Write("CallMethod被执行2");
            });

            //3.0               去掉delegate关键字,换成 在参数括号后面写 "=>"符号
            DelegateMethod method3 = new DelegateMethod( () =>
            {
                Console.Write("CallMethod被执行3");
            });

            //带参数形式
            DelegateMethod2 method4 = new DelegateMethod2((int x, int y) =>
            {
                Console.Write($"CallMethod被执行4 x:{x} y:{y}");
            });
            
            //省略参数类型  自动推算的
            DelegateMethod2 method5 = new DelegateMethod2((x, y) =>
            {
                Console.Write($"CallMethod被执行5 x:{x} y:{y}");
            });

            //如果方法体只有一行,省略大括号和分号
            DelegateMethod2 method6 = new DelegateMethod2((x, y) => Console.Write($"CallMethod被执行6 x:{x} y:{y}"));
            
            //省略 new DelegateMethod2,编译器推算
            DelegateMethod2 method7 =    ((x, y) => Console.Write($"CallMethod被执行6 x:{x} y:{y}"));

        }

      //被委托回调的方法
        private void CallMethod()
        {
            Console.Write("CallMethod被执行");
        }
        private void CallMethod2(int x, int y)
        {
            Console.Write("CallMethod2被执行 x:" + x.ToString() + " y:" + y.ToString());
        }

      //为了防止滥用委托,微软后来定义了一个统一规范,那就是 Action(不带返回值)和Func(带返回值)
      //就无需我们定义 private delegate void DelegateMethod(); 这样的形式的代码。
      //可在使用的地方直接初始化委托,在接收委托的方法参数类型上进行统一

      public void Test2()
      {
        Action method8 = () => Console.Write("这是无参无返回值委托初始化");
        Action<int> method9 = (x) => Console.Write("这是有参无返回值委托初始化 x:" + x);

 
  

        Func<int> method10 = () => 1; //这是无参带返回值int的委托
        Func<int, string> method11 = (x) => x.ToString(); //这是有参带返回值string类型的委托

 
  

        this.DoNothing(method8);
      }

 
  

      public void DoNothing(Action method)
      {

      }

  

 

转载于:https://www.cnblogs.com/BenPaoWoNiu/p/11388482.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值