C#:委托,匿名方法以及Lambda表达式

参考自https://www.cnblogs.com/chenwolong/p/5666196.html


委托:

实质为引用方法的对象,所以参数需要与所引用方法的参数一致;


//委托类型
delegate int calculator(int x, int y);
//创建委托对象
calculator Add = calculator(Adding);
//使用该委托对象
Console.WriteLine("{0}",Add(1,2)); //输出3
//委托引用方法
public static int Adding(int x,int y) return x + y;

匿名方法:

与委托结合使用;


//委托类型
delegate int calculator(int x, int y);
//创建匿名方法
calculator Adding =delegate( int x, int y)
{
    return x+y;
}
//使用
Console.WriteLine("{0}",Adding(1,2));//输出3

Lambda表达式

(参数)=>具体方法块, ( x , y ) => x + y  等效于 fun(x,y) return x+y ;


//委托类型
delegate int calculator(int x, int y);
//Lambda表达式
calculator Add = (x, y) => x + y;
//使用
Console.WriteLine("{0}", Add(1, 2));//输出3

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值