委托——Delegate.CreateDelegate()

作者:追风剑情 发布于:2019-7-8 16:02 分类:C#

示例


  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Reflection;
  6.  
  7. namespace ReflectionMethodsCache
  8. {
  9. class Program
  10. {
  11. //将方法缓存为委托,比通过反射调用Invoke()效率高
  12. public delegate void Fun1();
  13. public delegate void Fun2(string arg);
  14. public delegate void Fun3();
  15. public delegate void Fun4();
  16. public static Fun1 f1;
  17. public static Fun2 f2;
  18. public static Fun3 f3;
  19. public static Fun4 f4;
  20.  
  21. static void Main(string[] args)
  22. {
  23. Type type = typeof(ClassA);
  24. //firstArgument=null,则把委托作为static方法
  25. MethodInfo methodInfo = type.GetMethod("Fun1");
  26. if (methodInfo != null)
  27. {
  28. f1 = (Fun1)Delegate.CreateDelegate(typeof(Fun1), null, methodInfo);
  29. f1();
  30. }
  31.  
  32. methodInfo = type.GetMethod("Fun2");
  33. if (methodInfo != null)
  34. {
  35. f2 = (Fun2)Delegate.CreateDelegate(typeof(Fun2), null, methodInfo);
  36. f2("xxx");
  37. }
  38.  
  39. methodInfo = type.GetMethod("Fun3");
  40. if (methodInfo != null)
  41. {
  42. f3 = (Fun3)Delegate.CreateDelegate(typeof(Fun3), null, methodInfo);
  43. f3();
  44. }
  45.  
  46. //用指定的实例方法创建委托,这样创建出来的委托可访问实例变量
  47. ClassA classA = new ClassA();
  48. classA.i = 50;
  49. type = classA.GetType();
  50. methodInfo = type.GetMethod("Fun1");
  51. if (methodInfo != null)
  52. {
  53. f1 = (Fun1)Delegate.CreateDelegate(typeof(Fun1), classA, methodInfo);
  54. f1();
  55. }
  56.  
  57. methodInfo = type.GetMethod("Fun4");
  58. if (methodInfo != null)
  59. {
  60. f4 = (Fun4)Delegate.CreateDelegate(typeof(Fun4), classA, methodInfo);
  61. f4();//此委托可访问classA中的实例变量
  62. }
  63.  
  64. Console.ReadKey();
  65. }
  66. }
  67.  
  68. public class ClassA
  69. {
  70. public int i = 0;
  71.  
  72. public void Fun1()
  73. {
  74. Console.WriteLine("call Fun1");
  75. }
  76.  
  77. public void Fun2(string arg)
  78. {
  79. Console.WriteLine("call Fun2, arg={0}", arg);
  80. }
  81.  
  82. public static void Fun3()
  83. {
  84. Console.WriteLine("call static Fun3");
  85. }
  86.  
  87. public void Fun4()
  88. {
  89. Console.WriteLine("call Fun4, i={0}", i);
  90. }
  91. }
  92.  
  93. public class ClassB
  94. {
  95.  
  96. }
  97. }


运行测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号