delegate类型

 1  // delegate类型是C#语言另一个创新的技巧,它是一种数据结构,提供类似C++中函数指针(Function Pointer)的功能
 2  // delegate类型是面向对象函数指针(Object-Oriented Function Pointer).不过,不同的是C++的函数指针只能够指向静
 3  // 态的方法,而delegate除了可以指向静态的方法之外,还可以指向对象实体的方法.而最大的差别在于delegate是完全面向
 4  // 对象、具类型安全性、且使用安全的类型。另外,delegate可以在执行时期传入方法的名称,动态地决定欲调用的方法。
 5 
 6  // 语法介绍:
 7  // [attributes] [modifiers] delegate result-type identifier ([formal-parameters]);
 8  // 其中: 
 9 
10  // attributes(可选) 
11  // 附加的声明性信息。有关属性和属性类的更多信息,请参见 17. 属性。 
12  // modifiers(可选) 
13  // 允许使用的修饰符有 new 和四个访问修饰符。 
14  // result-type 
15  // 同方法的返回类型匹配的结果类型。 
16  // identifier 
17  // 委托名称。 
18  // formal-parameters(可选) 
19  // 参数列表。如果参数是一个指针,则必须用 unsafe 修饰符声明委托。 
20 
21  // 1.声明delegate类型
22  // 2.定义欲调用的方法
23  // 3.定义delegate类型处理函数,使用delegate
24  // 4.建立delegate类型实体,传入欲调用的方法名称
25  // 5.将程序代码连接起来
26 
27  // 接下来通过实例来演示怎么使用delegate
28  using  System;
29 
30  namespace  ConsoleApplication1
31  {
32       //  1.定义delegate类型:FunctionPointer
33       public   delegate   string  FunctionPointer( string  Name);
34      
35       public   class  Text
36      {
37           //  2.定义欲调用方法:F1 和 F2
38           public   static   string  F1( string  Name)
39          {
40               return   " A Say:My name is  "   +  Name;
41          }
42           public   static   string  F2( string  Name)
43          {
44               return   " B Say:My name is  "   +  Name  +   "  too " ;
45          }
46           //  3.定义delegate类型处理函数:PrintMethod
47           public   static   void  PrintMethod(FunctionPointer tempF)
48          {
49              Console.Write(tempF( " CIPC " ));
50          }
51           public   static   void  Main()
52          {
53               //  4.建立delegate类型实体:a 和 b ,传入欲调用的方法名称
54              FunctionPointer a  =   new  FunctionPointer(F1);
55              FunctionPointer b  =   new  FunctionPointer(F2);
56               //  5.将程序代码连接起来
57              PrintMethod(a);
58              PrintMethod(b);
59              
60          }
61      }
62  }
63 
64  //  首先定义一个实体 a 以后,调用处理函数:PrintMethod(a) ,此时 tempF 指向方法:F1 并将 tempF("CIPC") 中的string类型
65  //  "CIPC"传递给 F1 的参数 Name , 执行完 F1 方法后,返回“A Say:My name is CIPC"给PrintMethod并执行,打印

转载于:https://www.cnblogs.com/c-ipc/archive/2006/01/05/311896.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值