CSharp - 委托

2022年05月30日 · 笔记 · CSharp · 384次阅读

委托(Delegate)

委托(Delegate)就是一个引用变量

委托(Delegate)特别用于实现事件和回调方法。

声明委托

// 一个参数一个返回值的委托声明
public delegate int MyDelegate (string s);
//无返回值 一个object参数的委托声明
public delegate void MyDelegate (object s);

上例子声明了一个,一个参数一个返回值的委托函数。

声明形式:

delegate <return type> <delegate-name> <parameter list>

实例化委托

委托必须使用 new 关键字来创建,并且new 的构造函数中,必须有一个特定的方法,其方法的形参返回值与委托声明相同,如:

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

上面的实例化的ps1 和 ps2 ,可以当做函数来调用。

委托的多播

一个委托对象,可以使用 + 来绑定多个委托实例,所有委托实例参数必须相同,同样,也可以使用-来解除绑定。

绑定过后,使用委托对象使用,函数方法调用队列,是和绑定顺序相同的执行方式,通过+来绑定的实例委托是一个调用列表。这被称为委托的 多播(multicasting),也叫组播。

using System;

delegate int NumberChanger(int n);
namespace DelegateAppl
{
   class TestDelegate
   {
      static int num = 10;
      public static int AddNum(int p)
      {
         num += p;
         return num;
      }

      public static int MultNum(int q)
      {
         num *= q;
         return num;
      }
      public static int getNum()
      {
         return num;
      }

      static void Main(string[] args)
      {
         // 创建委托实例
         NumberChanger nc;
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);
         nc = nc1;
         nc += nc2;
         // 调用多播
         nc(5);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}

委托用途

using System;
using System.IO;

namespace DelegateAppl
{
   class PrintString
   {
      static FileStream fs;
      static StreamWriter sw;
      // 委托声明
      public delegate void printString(string s);

      // 该方法打印到控制台
      public static void WriteToScreen(string str)
      {
         Console.WriteLine("The String is: {0}", str);
      }
      // 该方法打印到文件
      public static void WriteToFile(string s)
      {
         fs = new FileStream("c:\\message.txt", FileMode.Append, FileAccess.Write);
         sw = new StreamWriter(fs);
         sw.WriteLine(s);
         sw.Flush();
         sw.Close();
         fs.Close();
      }
      // 该方法把委托作为参数,并使用它调用方法
      public static void sendString(printString ps)
      {
         ps("Hello World");
      }
      static void Main(string[] args)
      {
         printString ps1 = new printString(WriteToScreen);
         printString ps2 = new printString(WriteToFile);
         sendString(ps1);
         sendString(ps2);
         Console.ReadKey();
      }
   }
}

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

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

标签:C#

最后编辑于:2022-06-05 22:13

评论

搜一搜

云资源站点