c#匿名方法用途_C#的匿名方法

匿名方法是在初始化委托时内联声明的方法。

例如下面这两个例子:

不使用匿名方法的委托:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceConsoleApplication7

{classProgram

{public static int add(int x)

{

return x + 20;

}delegate int otherdel(intparam);public static voidMain()

{

otherdel del=add;

Console.WriteLine("{0}", del(20));

Console.WriteLine("{0}", del(10));

}

}

}

使用匿名方法的委托:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceConsoleApplication7

{classProgram

{delegate int otherdel(intparam);public static voidMain()

{

otherdel del= delegate(int x)

{

return x + 20;

};

Console.WriteLine("{0}", del(20));

Console.WriteLine("{0}", del(10));

}

}

}

两种结果是一样的。

使用匿名方法

1)声明委托变量时候作为初始化表达式。

2)组合委托时在赋值语句的右边。

3)为委托增加事件时在赋值语句的右边。

匿名方法语法

delegate (parameters ){implementationcode};

关键字  参数        语句块

匿名方法不会声明返回值类型。但是匿名方法返回值类型必须和委托返回值一样。

参数:参数数量,类型和修饰符必须和委托一样。

但是我们可以使圆括号为空,或省略圆括号来简化匿名方法的参数列表。但是仅在下面两项都为真的情况下才可以这么做。

1,委托的参数列表不包含任何out参数的委托。

2,匿名方法不使用任何参数。

例如下面:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceConsoleApplication7

{classProgram

{delegate int otherdel(intparam);public static voidMain()

{

otherdel del= delegate{

cleanup();

printMessage();

};

}

}

}

params参数:

如果委托参数包含params参数,那么params关键字就会被匿名方法的参数列表忽略。如下:

delegate int otherdel(int x,params inty);

otherdel del= delegate(int x,inty)

{-------------};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值