Program.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.Remoting.Messaging;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace ConsoleDelegateAnonymous
  8. {
  9. class Test
  10. {
  11. public int Add(int x, int y)
  12. {
  13. return x + y;
  14. }
  15. }
  16. internal class Program
  17. {
  18. //定义委托
  19. public delegate int DAdd(int x, int y);
  20. static void Main(string[] args)
  21. {
  22. Test test = new Test();
  23. //将委托与Add方法相关联
  24. DAdd d = test.Add;
  25. //再想调用Test类中的Add方法时,直接调用委托就可以了
  26. int num = d(2, 3);
  27. Console.WriteLine("num:" + num);
  28. //定义匿名方法(大括号外需要加分号)
  29. DAdd d1 = delegate(int x,int y)
  30. {
  31. //由于定义委托时有返回值类型,因此在定义匿名方法时
  32. //也一定要有返回值为相同类型的语句
  33. return x + y;
  34. };
  35. //调用
  36. int num2 = d1.Invoke(5, 6);
  37. Console.WriteLine("num2:" + num2);
  38. Console.ReadLine();
  39. }
  40. }
  41. }