11.2 委托的声明 - 图1委托是一种类:

    1. static void Main(string[] args)
    2. {
    3. Type t = typeof(Action);
    4. Console.WriteLine(t.IsClass);
    5. }

    11.2 委托的声明 - 图2
    委托是类,所以声明位置是和 class 处于同一个级别。但 C# 允许嵌套声明类(一个类里面可以声明另一个类),所以有时也会有 delegate 在 class 内部声明的情况。

    实例:

    1. public delegate double Calc(double x, double y);
    2. class Program
    3. {
    4. static void Main(string[] args)
    5. {
    6. Calculator calculator = new Calculator();
    7. Calc calc1 = new Calc(calculator.Add);
    8. Calc calc2 = new Calc(calculator.Sub);
    9. Calc calc3 = new Calc(calculator.Mul);
    10. Calc calc4 = new Calc(calculator.Div);
    11. double a = 100;
    12. double b = 200;
    13. double c = 0;
    14. c = calc1.Invoke(a, b);
    15. Console.WriteLine(c);
    16. c = calc2.Invoke(a, b);
    17. Console.WriteLine(c);
    18. c = calc3.Invoke(a, b);
    19. Console.WriteLine(c);
    20. c = calc4.Invoke(a, b);
    21. Console.WriteLine(c);
    22. }
    23. }
    24. class Calculator
    25. {
    26. public double Add(double x,double y)
    27. {
    28. return x + y;
    29. }
    30. public double Sub(double x, double y)
    31. {
    32. return x - y;
    33. }
    34. public double Mul(double x, double y)
    35. {
    36. return x * y;
    37. }
    38. public double Div(double x, double y)
    39. {
    40. return x / y;
    41. }
    42. }