匿名方法是在初始化委托时内联声明的方法。
例如下面这两个例子:
不使用匿名方法的委托:
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)
{-------------};