c# 匿名方法
来源:互联网 发布:太平洋网络股票 编辑:程序博客网 时间:2024/06/05 10:53
匿名方法是在初始化委托时内联声明的方法。
例如下面这两个例子:
不使用匿名方法的委托:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication7{ class Program { public static int add(int x) { return x + 20; } delegate int otherdel(int param); public static void Main() { otherdel del = add; Console.WriteLine("{0}", del(20)); Console.WriteLine("{0}", del(10)); } } }
使用匿名方法的委托:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication7{ class Program { delegate int otherdel(int param); public static void Main() { 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,匿名方法不使用任何参数。
例如下面:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication7{ class Program { delegate int otherdel(int param); public static void Main() { otherdel del = delegate { cleanup(); printMessage(); }; } } }
params参数:
如果委托参数包含params参数,那么params关键字就会被匿名方法的参数列表忽略。如下:
delegate int otherdel(int x,params int y); otherdel del = delegate(int x,int y) { ------------- };
阅读全文
0 0
- C#匿名方法zz
- C#的匿名方法
- C#基础:匿名方法
- c# 匿名方法
- C#的匿名方法
- C#匿名方法
- C# 匿名方法 委托
- C#匿名方法
- c#匿名方法
- C# 匿名方法
- c#的匿名方法
- C#匿名方法
- C# 匿名方法
- c#匿名方法
- C#匿名方法
- c# 匿名方法
- 关于C#匿名方法
- C# 匿名方法
- 习题8.1 银行排队问题之单队列多窗口服务
- Redis与Memcached的比较
- BZOJ 1084 [SCOI 2005] DP 解题报告
- 安装docker
- php cgi 模式下 获取不到 $argv 解决方案
- c# 匿名方法
- 欢迎使用CSDN-markdown编辑器
- PRM路径规划算法
- 从《我的前半生》看项目经理如何年入百万—光环国际PMP
- java的递归IO读取操作
- Java学习第二课
- Fresco解析 (初始化)
- android事件处理,对事件的接收处理,(6)
- tesseract 字符识别开源工程介绍