C# 匿名方法:简化委托使用的实用技巧
匿名方法简介
我们之前讨论过,委托用于引用与委托具有相同签名的任何方法。换句话说,你可以使用委托对象调用可被委托引用的方法。
匿名方法提供了一种将代码块作为委托参数传递的技术。匿名方法没有名称,只有方法体。
在匿名方法中无需指定返回类型;它从方法体内的 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) {
// 使用匿名方法创建委托实例
NumberChanger nc = delegate(int x) {
Console.WriteLine("Anonymous Method: {0}", x);
};
// 使用匿名方法调用委托
nc(10);
// 使用命名方法实例化委托
nc = new NumberChanger(AddNum);
// 使用命名方法调用委托
nc(5);
// 使用另一个命名方法实例化委托
nc = new NumberChanger(MultNum);
// 使用命名方法调用委托
nc(2);
Console.ReadKey();
}
}
}
编译执行上述代码,输出结果如下:
Anonymous Method: 10 Named Method: 15 Named Method: 30
C语言