Action 和 Func 是 C# 内置的委托实例,它们都有很多重载以方便使用。

    1. class Program
    2. {
    3. static void Main(string[] args)
    4. {
    5. Calculator calculator = new Calculator();
    6. Action action = new Action(calculator.Report);
    7. calculator.Report();//直接调用Report方法
    8. action.Invoke();//间接调用Report方法
    9. action();//简便写法
    10. Func<int, int, int> func1 = new Func<int, int, int>(calculator.Add);
    11. Func<int, int, int> func2 = new Func<int, int, int>(calculator.Sub);
    12. int x = 100;
    13. int y = 200;
    14. int z = 0;
    15. //z = func1.Invoke(x, y);
    16. z = func1(x, y);
    17. Console.WriteLine(z);
    18. //z = func2.Invoke(x, y);
    19. z = func2(x, y);
    20. Console.WriteLine(z);
    21. }
    22. }
    23. class Calculator
    24. {
    25. public void Report()
    26. {
    27. Console.WriteLine("I have 3 methods.");
    28. }
    29. public int Add(int a,int b)
    30. {
    31. int result = a + b;
    32. return result;
    33. }
    34. public int Sub(int a, int b)
    35. {
    36. int result = a - b;
    37. return result;
    38. }
    39. }