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

简介:
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   
相关文章
|
1月前
调用反射类的方法
调用反射类的方法
16 3
|
1月前
调用反射类的指定方法
调用反射类的指定方法
12 3
|
1月前
深入类的方法
深入类的方法
8 0
|
3月前
|
C++
c++将一个类的回调函数注入到另一个类中的方法
c++将一个类的回调函数注入到另一个类中的方法
|
9月前
|
开发框架 .NET
实例化对象时的()什么意思?
实例化对象时的()什么意思?
|
11月前
|
设计模式 Python
我为什么要创建一个不能被实例化的类
我为什么要创建一个不能被实例化的类
40 0
|
C++
同样一句代码,在类内调用,跟类外调用结果不同?
同样一句代码,在类内调用,跟类外调用结果不同?
62 0
|
C++ 小程序
c++类的实例化,有没有new的区别
A a; A * a = new a(); 以上两种方式皆可实现类的实例化,有new的区别在于: 1.前者在堆栈中分配内存,后者为动态内存分配,在一般应用中是没有什么区别的,但动态内存分配会使对象的可控性增强。
1168 0
|
Python
类的方法总结
[root@blackfox zhouyuyao]# cat c8.py  #!/usr/bin/python #coding:utf8 class MyClass(object):     name = 'Test'     def __init__(self):         self.
683 0