c# lamada表达式推演

//lamada表达式是什么? 左边是参数列表 goes to语法 右边是方法体,本质就是一个方法
//      lamada不是委托,因为委托是一个类型
//      也不是委托的示例,因为这里省略了 new 委托()
//      他的作用:是一个方法
//         编译后:lamada 实际上会生成一个类中类里面的一个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());
        }

猜你喜欢

转载自www.cnblogs.com/BenPaoWoNiu/p/11388482.html
今日推荐