语法解析
以关键字delegate开头;后跟小括号提供参数;再后跟{}作为语句块
delegate (Parameters) {ImplementationCode}
- 匿名方法不会显示的声明返回类型delegate (int x) { return x;}即为返回一个int类型的值
- 参数的数量、位置、类型、修饰符必须与委托相匹配
-
可以通过省略圆括号或使圆括号为空来简化匿名方法的参数列表,前提是参数是不包含out参数,方法体中不使用任何参数
示例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeForDelegate { //定义委托类型 delegate void MyDel(ref int x); class Program { static void Add1(ref int x) { x += 1; } static void Add2(ref int x) { x += 2; } static void Main(string[] args) { Program program = new Program(); //采用匿名方法形式代替具名方法 MyDel del = delegate(ref int y) { y += 3; }; del += Add1; del += Add2; //匿名方法未使用任何参数,简化形式 del += delegate{int z = 10;}; //ref会将x当作引用值传递给委托方法 int x = 5; del(ref x); Console.ReadKey(); } } }如果定义一个带有params形式的参数,在使用匿名方法的时候可以省略params关键字以简化代码
示例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeForDelegate { //定义一个带有params形式参数的委托类型 delegate void DelFunction(int x, params int[] z); class Program { static void Main(string[] args) { Program program = new Program(); // 关键字params被忽略(省略关键字以简化) DelFunction df = delegate(int x, int[] y) { ... }; Console.ReadKey(); } } }










