.net委托

声明委托:

在C#中要使用一个类时分两个阶段,1.定义这个类 2.实例化这个类 委托也需要这个过程

1.定义一个委托 2.实例化一个或多个委托

语法:

delegate void IntMethodInvoker(int x);

 委托是类型安全的所以在定义委托时必须给出他所表示的方法的签名和返回类型等所有细节。

 委托也可以理解成他给方法的签名和返回类型指定名称。

其语法类似于定义一个新类,所以可以在定义类的任何地方定义委托。

 

View Code
 1  delegate string str();
2
3 static void Main(string[] args)
4 {
5 int num = 6;
6 str str = new str(num.ToString);
7 Console.WriteLine(str());
8 Console.Read();
9
10 }

str str = new str(num.ToString); 初始化委托str(num.ToString); 表示引用num的ToString的方法。

因为num.ToString()是一个实例方法(不是静态方法),所以需要指定实例(x)和方法的签名来正确的初始化委托。

str str = num.ToString;也可以直接将方法指定给委托和str str = new str(num.ToString);是等效的。

 

View Code
 1   public delegate double OprNum(double num);
2 class Program
3 {
4
5 public static double Opr(double num)
6 {
7 return num * num;
8 }
9
10 public static double OprTwo(double num)
11 {
12 return num * 2;
13 }
14
15 static void Main(string[] args)
16 {
17 OprNum[] op = { Opr, OprTwo };
18
19 for (int i = 0; i < op.Length;i++ )
20 {
21 Console.WriteLine(Reult(op[i],2));
22 Console.WriteLine(Reult(op[i], 42));
23 }
24
25 Console.Read();
26
27 }
28
29 public static double Reult(OprNum op, double num)
30 {
31 return op(num);
32 }
33 }

委托是个类所以把委托的实例放在数组中是可以的。

 Action<T>和Func<T>委托

 

posted @ 2012-03-18 13:52  猪特曼  阅读(245)  评论(0编辑  收藏  举报