lambda演变历史

    class LandmadaShow
    {
        public delegate void NoReturnWithPara(string name);

        //lambda演变历史
        public void Show()
        {

            {
                //.NetFramework1.0  1.1
                NoReturnWithPara noReturnWithPara = new NoReturnWithPara(this.DoNothing);
                noReturnWithPara.Invoke("王大师");
            }
            int i = 10;
            {
                //.NetFramework2.0  匿名方法,delegate关键字
                //可以访问局部变量
                NoReturnWithPara noReturnWithPara = new NoReturnWithPara(delegate (string name)
                {
                    Console.WriteLine(name);
                    Console.WriteLine(i);
                });
                noReturnWithPara.Invoke("王大师");
            }

            {
                //.NetFramework3.0   把delegate关键字去掉,增加了一个箭头goes to
                //lambda表达式  参数列表=>方法体
                NoReturnWithPara noReturnWithPara = new NoReturnWithPara((string name) =>
               {
                   Console.WriteLine(name);
                   Console.WriteLine(i);
               });
                noReturnWithPara.Invoke("王大师");
            }

            {
                //省略参数类型,编译器的语法糖,虽然没写,编译时还是有的,根据委托推算
                NoReturnWithPara noReturnWithPara = new NoReturnWithPara((name) =>
                {
                    Console.WriteLine(name);
                });
                noReturnWithPara.Invoke("王大师");
            }

            {
                //如果方法体只有一行,可以去掉大括号和分号
                NoReturnWithPara noReturnWithPara = new NoReturnWithPara((name) => Console.WriteLine(name));
                noReturnWithPara.Invoke("王大师");
            }

            {
                //new NoReturnWithPara可以省掉,也是语法糖,编译器自动加上
                NoReturnWithPara noReturnWithPara = (name) => Console.WriteLine(name);
                noReturnWithPara.Invoke("王大师");
            }

        }
        public void DoNothing(string name)
        {
            Console.WriteLine(name);
        }
    }

 

posted @ 2019-11-09 14:47  王大师123  阅读(217)  评论(0编辑  收藏  举报