Program.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. namespace DelegateDemo
  3. {
  4. class Program
  5. {
  6. /// <summary>
  7. /// 泛型委托
  8. /// </summary>
  9. /// <typeparam name="T"></typeparam>
  10. /// <typeparam name="S"></typeparam>
  11. /// <param name="a"></param>
  12. /// <param name="b"></param>
  13. /// <returns></returns>
  14. public delegate int ProcessDelegate<T, S, V>(T a, S b, V v);
  15. /// <summary>
  16. /// 委托
  17. /// </summary>
  18. /// <param name="a"></param>
  19. /// <param name="b"></param>
  20. /// <returns></returns>
  21. public delegate int ProcessDelegate(int a, int b);
  22. static void Main(string[] args)
  23. {
  24. //静态调用
  25. ProcessDelegate process = new ProcessDelegate(Add);
  26. ProcessDelegate<int, int, int> processDelegate = new ProcessDelegate<int, int, int>(Add);
  27. var a = processDelegate(5, 5, 5);
  28. Console.WriteLine(process(2, 4));
  29. Console.WriteLine(Calculate(4, 3, Add ));
  30. Console.WriteLine(Calculate(4, 3,5, Add));
  31. Console.WriteLine(a);
  32. //实例调用
  33. Test test = new Test();
  34. ProcessDelegate processA = new ProcessDelegate(test.Add);
  35. Console.WriteLine(processA(5, 8));
  36. ProcessDelegate processB = (ProcessDelegate)Delegate.Combine(process , processA);
  37. //调用了Delegate.Combine()方法,通过名称可以指定它用于将多个委托组合起来,调用test3时,会按照它的参数顺序执行所有方法。这种方式有时候非常有用,因为我们很可能在某个事件发生时,要执行多个操作。
  38. Console.WriteLine(Calculate(50, 10, processB));
  39. //Func调用从无参到16个参数共有17个重载,用于分装有输入值而且有返回值的方法。如:delegate TResule Func<T>(T obj);
  40. Func<int, int, int> func = new Func<int, int, int>(Add);
  41. //Action 从无参到16个参数共有17个重载,用于分装有输入值而没有返回值的方法。如:delegate void Action<T>(T obj);
  42. Action<int, int> action = new Action<int, int>(test.Say);
  43. Console.WriteLine(func(5, 9));
  44. }
  45. //执行委托
  46. public static int Calculate(int a, int b, ProcessDelegate process) {
  47. return process(a, b);
  48. }
  49. public static int Calculate(int a, int b, int c , ProcessDelegate<int , int ,int > process)
  50. {
  51. return process(a, b , c);
  52. }
  53. public static int Add(int a, int b)
  54. {
  55. return a + b;
  56. }
  57. public static int DS(int a, int b)
  58. {
  59. return a + b;
  60. }
  61. public static int Add(int a, int b, int c)
  62. {
  63. return a + b + c;
  64. }
  65. }
  66. public class Test {
  67. public int Add(int a, int b) {
  68. return a + b;
  69. }
  70. public void Say(int a, int b)
  71. {
  72. Console.WriteLine(a + b);
  73. }
  74. }
  75. }