C#委托

C# 委托(Delegate)

C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。委托(Delegate) 是存有对某个方法的引用的一种引用类型变量。引用可在运行时被改变。

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

声明委托(Delegate)

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

例如,假设有一个委托:

[csharp]  view plain  copy
  1. public delegate int MyDelegate (string s);  

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

声明委托的语法如下:

[csharp]  view plain  copy
  1. delegate <return type> <delegate-name> <parameter list>  

实例化委托(Delegate)

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

[csharp]  view plain  copy
  1. public delegate void printString(string s);  
  2. ...  
  3. printString ps1 = new printString(WriteToScreen);  
  4. printString ps2 = new printString(WriteToFile);  

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

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

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

[csharp]  view plain  copy
  1. Value of Num: 35  
  2. Value of Num: 175  

委托的多播(Multicasting of a Delegate)

委托对象可使用 "+" 运算符进行合并。一个合并委托调用它所合并的两个委托。只有相同类型的委托可被合并。"-" 运算符可用于从合并的委托中移除组件委托。

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

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

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

[csharp]  view plain  copy
  1. Value of Num: 75  

委托多播例子:

[csharp]  view plain  copy
  1. using System;  
  2. // MOBA游戏中的菜鸟玩家  
  3. public class CaiNiao  
  4.     {  
  5.     // 菜鸟的职业修养  
  6.     public static void SongRenTou()  
  7.     {  
  8.             Console.WriteLine("已练成花式极限千里送人头方法");  
  9.     }  
  10.     public static void PenDuiYou()  
  11.     {  
  12.         Console.WriteLine("精通各种辱骂队友方式");  
  13.     }  
  14. }  
  15.   
  16. class Player  
  17. {  
  18.     // 菜鸟的常规操作  
  19.     public delegate void CaiNiaoAction();  
  20.   
  21.     public static void Main(string[] args)  
  22.     {  
  23.         //菜鸟的极限操作  
  24.         CaiNiaoAction myDelegate = new CaiNiaoAction(CaiNiao.SongRenTou);  
  25.         myDelegate += CaiNiao.PenDuiYou;  
  26.         // 这时候委托被附上了具体的方法  
  27.         myDelegate();  
  28.         Console.ReadKey();  
  29.     }  
  30. }  
输出结果为:

[csharp]  view plain  copy
  1. 已练成花式极限千里送人头方法  
  2. 精通各种辱骂队友方式  


委托(Delegate)的用途

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

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

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

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

[csharp]  view plain  copy
  1. The String is: Hello World  

猜你喜欢

转载自blog.csdn.net/weixin_39029925/article/details/78246631