委托的创建、实例化和调用

C#代码   收藏代码
  1. <p>通过使用 Delegate 类,委托实例可以封装属于可调用实体的方法。</p><p>对于实例方法,委托由一个包含类的实例和该实例上的方法组成。</p><p>对于静态方法,可调用实体由一个类和该类上的静态方法组成。</p><p>因此,委托可用于调用任何对象的函数,而且委托是面向对象的、类型安全的。</p><p>定义和使用委托有三个步骤:</p>  
  • 声明

  • 实例化

  • 调用

C#代码   收藏代码
  1.   
C#代码   收藏代码
  1. <p><span style="color: #ff00ff;">C#可通过使用委托来确定在运行时选择要调用哪些函数。</span></p>  
C#代码   收藏代码
  1. 以下代码演示了委托的创建、实例化和调用:  
  2.   
  3. C#  复制代码   
  4. public class MathClass  
  5. {  
  6.     public static long Add(int i, int j)       // static  
  7.     {  
  8.         return (i + j);  
  9.     }  
  10.   
  11.     public static long Multiply (int i, int j)  // static  
  12.     {  
  13.         return (i * j);  
  14.     }  
  15. }  
  16.   
  17. class TestMathClass  
  18. {  
  19.     delegate long Del(int i, int j);  // declare the delegate type  
  20.   
  21.     static void Main()  
  22.     {  
  23.         Del operation;  // declare the delegate variable  
  24.   
  25.         operation = MathClass.Add;       // set the delegate to refer to the Add method  
  26.         long sum = operation(11, 22);             // use the delegate to call the Add method  
  27.   
  28.         operation = MathClass.Multiply;  // change the delegate to refer to the Multiply method  
  29.         long product = operation(30, 40);         // use the delegate to call the Multiply method  
  30.   
  31.         System.Console.WriteLine("11 + 22 = " + sum);  
  32.         System.Console.WriteLine("30 * 40 = " + product);  
  33.     }  
  34. }  
  35.   
  36.   
  37.    
  38.   
  39. 输出  
  40. 11 + 22 = 33   
  41.   
  42. 30 * 40 = 1200   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值