前面我们学习过,委托可用于引用任何与委托签名相同的方法。换句话说,可以调用可以由委托使用该委托对象引用的方法。
匿名方法提供了一种将代码块作为委托参数传递的技术。匿名方法是没有名称的方法,只有方法体。
不需要在匿名方法中指定返回类型; 它是从方法体中的return
语句来推断的。
使用delegate
关键字创建代理实例时,就可以声明匿名方法。 例如,
delegate void numberchanger(int n);
...
numberchanger nc = delegate(int x)
{
console.writeline("anonymous method: {0}", x);
};
代码块console.writeline("anonymous method: {0}", x);
是匿名方法体。
代理可以使用匿名方法和命名方法以相同的方式调用,即通过将方法参数传递给委托对象。
例如,
nc(10);
以下示例演示如何实现概念:
using system;
delegate void numberchanger(int n);
namespace delegateappl
{
class testdelegate
{
static int num = 10;
public static void addnum(int p)
{
num += p;
console.writeline("named method: {0}", num);
}
public static void multnum(int q)
{
num *= q;
console.writeline("named method: {0}", num);
}
public static int getnum()
{
return num;
}
static void main(string[] args)
{
//create delegate instances using anonymous method
numberchanger nc = delegate(int x)
{
console.writeline("anonymous method: {0}", x);
};
//calling the delegate using the anonymous method
nc(10);
//instantiating the delegate using the named methods
nc = new numberchanger(addnum);
//calling the delegate using the named methods
nc(5);
//instantiating the delegate using another named methods
nc = new numberchanger(multnum);
//calling the delegate using the named methods
nc(2);
console.readkey();
}
}
}
当上述代码被编译并执行时,它产生以下结果:
anonymous method: 10
named method: 15
named method: 30