委托(Delegate)特别用于实现事件和回调方法。所有的委托(Delegate)都派生自 System.Delegate 类。

    委托声明决定了可由该委托引用的方法。委托可指向一个与其具有相同标签的方法。

    例如,假设有一个委托:

    上面的委托可被用于引用任何一个带有一个单一的 string 参数的方法,并返回一个 int 类型变量。

    一旦声明了委托类型,委托对象必须使用 new 关键字来创建,且与一个特定的方法有关。当创建委托时,传递到 new 语句的参数就像方法调用一样书写,但是不带有参数。例如:

    1. public delegate void printString(string s);
    2. ...
    3. printString ps1 = new printString(WriteToScreen);
    4. printString ps2 = new printString(WriteToFile);

    下面的实例演示了委托的声明、实例化和使用,该委托可用于引用带有一个整型参数的方法,并返回一个整型值。

    当上面的代码被编译和执行时,它会产生下列结果:

    1. Value of Num: 35
    2. Value of Num: 175

    使用委托的这个有用的特点,您可以创建一个委托被调用时要调用的方法的调用列表。这被称为委托的 多播(multicasting),也叫组播。下面的程序演示了委托的多播:

    1. using System;
    2. delegate int NumberChanger(int n);
    3. namespace DelegateAppl
    4. {
    5. class TestDelegate
    6. {
    7. static int num = 10;
    8. public static int AddNum(int p)
    9. {
    10. num += p;
    11. return num;
    12. }
    13. public static int MultNum(int q)
    14. {
    15. num *= q;
    16. return num;
    17. }
    18. {
    19. return num;
    20. }
    21. static void Main(string[] args)
    22. {
    23. // 创建委托实例
    24. NumberChanger nc;
    25. NumberChanger nc1 = new NumberChanger(AddNum);
    26. NumberChanger nc2 = new NumberChanger(MultNum);
    27. nc = nc1;
    28. nc += nc2;
    29. // 调用多播
    30. nc(5);
    31. Console.WriteLine("Value of Num: {0}", getNum());
    32. Console.ReadKey();
    33. }
    34. }
    35. }

    当上面的代码被编译和执行时,它会产生下列结果:

    下面的实例演示了委托的用法。委托 printString 可用于引用带有一个字符串作为输入的方法,并不返回任何东西。

    我们使用这个委托来调用两个方法,第一个把字符串打印到控制台,第二个把字符串打印到文件:

    1. using System;
    2. using System.IO;
    3. namespace DelegateAppl
    4. {
    5. class PrintString
    6. {
    7. static FileStream fs;
    8. static StreamWriter sw;
    9. // 委托声明
    10. public delegate void printString(string s);
    11. // 该方法打印到控制台
    12. public static void WriteToScreen(string str)
    13. Console.WriteLine("The String is: {0}", str);
    14. }
    15. // 该方法打印到文件
    16. public static void WriteToFile(string s)
    17. {
    18. fs = new FileStream("c:\\message.txt",
    19. FileMode.Append, FileAccess.Write);
    20. sw = new StreamWriter(fs);
    21. sw.WriteLine(s);
    22. sw.Flush();
    23. sw.Close();
    24. fs.Close();
    25. }
    26. // 该方法把委托作为参数,并使用它调用方法
    27. public static void sendString(printString ps)
    28. {
    29. ps("Hello World");
    30. }
    31. static void Main(string[] args)
    32. {
    33. printString ps1 = new printString(WriteToScreen);
    34. printString ps2 = new printString(WriteToFile);
    35. sendString(ps1);
    36. sendString(ps2);
    37. Console.ReadKey();
    38. }
    39. }
    1. The String is: Hello World

    🔚