常规操作,我们要使用一个委托,需要有三个步骤:声明委托,定义委托变量,实例化委托。
using System; namespace ConsoleApplication2 { class Program { delegate int delAdd(int a,int b); static void Main(string[] args) { delAdd add = new delAdd(Add); int c = add(123,456); Console.WriteLine(c); } static int Add(int a,int b) { return a + b; } } } |
如果上述程序中的Add函数,我们可能就用一次或者只关联到一个委托变量上,是不是没有必要专门定义一个函数呢?这样就出现了匿名方法。
using System; namespace ConsoleApplication2 { class Program { delegate int delAdd(int a,int b); static void Main(string[] args) { delAdd add = delegate (int a, int b) { return a + b; }; int c = add(123,456); Console.WriteLine(c); } } } |
也许微软觉得匿名方法表达还是比较啰嗦,出现了Lambda表达式。程序可以写成下面这个样子了。
using System; namespace ConsoleApplication2 { class Program { delegate int delAdd(int a,int b); static void Main(string[] args) { delAdd add = (int a, int b) =>{ return a + b; }; int c = add(123,456); Console.WriteLine(c); } } } |
委托和泛型结合起来,出现了泛型委托,微软定义了两个泛型委托,无返回值的Action和有返回值的Func
namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Func<int,int,int> add = (int a, int b) =>{ return a + b; }; int c = add(123,456); Console.WriteLine(c); } } } |