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);};


转载于:https://www.cnblogs.com/wwxtju/p/4376084.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值