委托的几种表示方法

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace ConsoleApplication1
 7 {
 8 class Program
 9 {
10 //delegate string works(int a,int b);
11 static void Main(string[] args)
12 {
13 //第一种
14 // List<string> list = new List<string>() { "1111", "2", "3", "4" };
15 //list = list.FindAll(x => { bool flag = x.Length < 4; return flag; });
16 //list.ForEach(Console.WriteLine);
17 
18 //第二种
19 // works wk = new works(methord);
20 //Console.WriteLine(wk(2, 3));
21 
22 //第三种
23 //works wk = (x,y) => (x+y).ToString();
24 // Console.WriteLine(wk(3, 4));
25 
26 //自带的委托定义
27 
28 //Func<T>带有返回值的泛型委托
29 //泛型Func<T>委托与Action<T>委托类似,不同点是Func<T>允许调用带返回值类型的方法,
30 //而且其返回值类型的指定是Func<T1,T2,T3...Tn>中的最后一个类型(Tn),即Tn就是其返回值,
31 //其它类型都表示参数的类型。(最多可以有16种参数类型和一个返回值类型)
32 Func<int,int,string> fc = methord;
33 Console.WriteLine(fc(3, 5));
34 
35 //Action<T>无返回值的泛型委托
36 //泛型Action<T>委托表示引用一个void返回类型的方法,这个委托类可以有多个(≥0)参数且参数的类型可以不同(最多可以有16种不同类型的参数)。
37 Action<int,int> ac = methord1;
38 ac(3, 6);
39 
40 //Predicate<T>委托(常用于集合参数)
41 //Predicate<T>泛型委托,只能接受一个传入参数,返回值为bool类型。
42 Predicate<int> pr = Method2;
43 if (pr(3))
44 {
45 Console.WriteLine("偶数");
46 }
47 else
48 
49 {
50 Console.WriteLine("奇数");
51 }
52 
53 Console.Read();
54 
55 }
56 public static string methord(int a,int b)
57 { 
58 return (a+b).ToString();
59 }
60 public static void methord1(int a, int b)
61 {
62 Console.WriteLine( (a + b).ToString());
63 }
64 public static bool Method2(int a)
65 {
66 
67 if (a % 2 == 0)
68 {
69 
70 return true;
71 
72 }
73 return false;
74 
75 }
76 }
77 }

 

posted @ 2014-02-10 14:43  无处安放的青春  阅读(705)  评论(0编辑  收藏  举报