c#编程指南(三) 泛型委托(Generic Delegate)
c#编程指南(三) 泛型委托(Generic Delegate)
泛型委托实际上就是一个.NET Framework预定义的委托,基本涵盖了所有常用的委托,所以一般不用用户重新声明啦。
很简单,看下面简单的小例子:
1 //void method();
2 Action test1 = () => { Console.WriteLine("void method();"); };
3 //void method(x);
4 Action<int> test2 = (x) => { Console.WriteLine("void method(t1)"); };
5 //void method(x, y);
6 Action<int, int> test3 = (x, y) => { Console.WriteLine("void method(t1, t2)"); };
7
8 test1();
9 test2(1);
10 test3(2, 3);
2 Action test1 = () => { Console.WriteLine("void method();"); };
3 //void method(x);
4 Action<int> test2 = (x) => { Console.WriteLine("void method(t1)"); };
5 //void method(x, y);
6 Action<int, int> test3 = (x, y) => { Console.WriteLine("void method(t1, t2)"); };
7
8 test1();
9 test2(1);
10 test3(2, 3);
Action系列泛型委托,是没有返回参数的委托,我简单的举了一个无参数的委托,带一个参数的委托,还有带两个参数的委托。调用的时候和普通的委托没有声明两样。具体的方法我使用的是lambda写的,我前面文章有介绍。是不是很简单,不用自己在写public delegate void VoidDelegate();了。呵呵,简洁明了。
下面是有返回值的泛型委托:
1 //int method();
2 Func<int> test4 = () => 10;
3 //int method(int);
4 Func<int, int> test5 = (x) => x * 2;
5 //int method(int ,int);
6 Func<int, int, int> test6 = (x, y) => x * y;
7
8 Console.WriteLine(test4());
9 Console.WriteLine(test5(3));
10 Console.WriteLine(test6(4, 5));
2 Func<int> test4 = () => 10;
3 //int method(int);
4 Func<int, int> test5 = (x) => x * 2;
5 //int method(int ,int);
6 Func<int, int, int> test6 = (x, y) => x * y;
7
8 Console.WriteLine(test4());
9 Console.WriteLine(test5(3));
10 Console.WriteLine(test6(4, 5));
是不是很简单,Func系列的委托时有返回值的委托。但是在方便之余还是感叹下微软的鬼斧神工吧,哈哈!!
示例代码:下载