zoukankan      html  css  js  c++  java
  • c#系列之各种lambda表达式

    lambda表达式说白了就是一个匿名函数。

    使用场景,举个例子吧,就像我自己写Android程序时,如果要绑定点击事件,经常要写一大堆几乎一样的格式的代码,而这些代码基本上没有复用,所以也没办法写一个函数啊,类啊来讲话过程。

    而lambda就是一个折中的办法,在你写一个函数,且只用在一个地方的时候,你可以写这样一个函数来简化。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication3
    {
        delegate void test();
        delegate void test2(int x);
        class Program
        {
            static void Main(string[] args)
            {
                test mytest = delegate() { Console.WriteLine("wwx use the first"); };
                mytest += ()=> {Console.WriteLine("wwx use the second");};
              
                test2 mytest2 = delegate(int x) { Console.WriteLine("wwx use the first use the {0}",x);};
                mytest2 += (x) => {Console.WriteLine("wwx use the second use the {0}",x);};
                mytest2 += x =>{Console.WriteLine("wwx use the third use the {0}",x);};
                mytest2 += x => Console.WriteLine("use the four use the {0}",x);
    
                mytest();
                mytest2(2);
            }
        }
    }
    


    
    

    有几个特点,对于只有一个参数的话,甚至可以不写括号而且如果不是out,ref这样的参数,可以不加类型(多个变量),如果方法体只有一句话,那么可以不写大括号。

    mytest2 += (x,y) => {Console.WriteLine("wwx use the second use the {0}",x);};


  • 相关阅读:
    使用kendynet构建异步redis访问服务
    使用kendynet编写网关服务
    作为前端,我为什么选择 Angular 2?
    你必须知道的Javascript 系列
    JS日期(Date)处理函数总结
    JS数组(Array)处理函数总结
    消息推送之APNS
    消息推送之GCM
    Linux常用命令大全
    Sequential Container
  • 原文地址:https://www.cnblogs.com/wwxtju/p/4376084.html
Copyright © 2011-2022 走看看