我希望你是我独家记忆

一段永远封存的记忆,随风而去
posts - 263, comments - 31, trackbacks - 0, articles - 3
   :: 首页 :: 新随笔 ::  :: 聚合  :: 管理

委托实例

Posted on 2009-07-07 14:52 Hero 阅读(177) 评论(0)  编辑 收藏 引用 所属分类: C#积累
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 using System.IO;
 5 
 6 namespace Stream_test
 7 {
 8     //定义两个静态方法
 9     class MathOP
10     {
11         public static double Multi2( double value )
12         {
13             return value * 2;
14         }
15 
16         public static double Square( double value )
17         {
18             return value * value;
19         }
20     }
21 
22     class Program
23     {
24         //声明委托类
25         delegate double DoubleOP( double value );
26 
27         //注意这里一定要是静态的
28         static void DisplayOP( DoubleOP action, double value )
29         {
30             double result = action( value );
31 
32             Console.WriteLine( "{0} op is {1}", value, result );
33         }
34 
35         static void Main( string[] args )
36         {
37             //创建匿名委托
38             DoubleOP OP3 = delegatedouble value )
39             {
40                 return value * value;
41             };
42 
43             //创建委托数组 -- 存储的是方法签名
44             DoubleOP[] deleOP = {
45                 new DoubleOP( MathOP.Multi2) ,
46                 new DoubleOP( MathOP.Square) ,
47                 OP3
48             };
49 
50             //可以将委托作为参数来传递
51             forint i=0; i<deleOP.Length; i++ )
52             {
53                 Console.WriteLine( "using deleOP[{0}]", i );
54                 DisplayOP( deleOP[i], 2.0 );
55                 DisplayOP( deleOP[i], 7.94 );
56                 DisplayOP( deleOP[i], 1.414 );
57                 Console.WriteLine();
58             }
59         }
60     }
61 }
62