Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Delegate


May 11, 2021 C#


Table of contents


Delegate

The delegate in C# is similar to a pointer to a function in C or C. is a reference type variable that contains a reference to a method. References can be changed at runtime.

Delegates are especially used to implement events and callback methods. All delegates are derived from the System.Delegate class.

Claim Delegate

A delegate declaration determines the method that can be referenced by the delegate. A delegate can point to a method that has the same label as it.

For example, suppose you have a delegate:

public delegate int MyDelegate (string s);

The above delegate can be used to refer to any method with a single string parameter and return an int type variable.

The syntax for declaring delegates is as follows:

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

Instantiation delegate

Once the delegate type is declared, the delegate object must be created using the new keyword and is related to a specific method. W hen a delegate is created, the arguments passed to the new statement are written like method calls, but without parameters. For example:

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

The following example demonstrates the declaration, instantiation, and use of a delegate that can be used to refer to a method with an integer parameter and return an integer value.

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 nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);
         // 使用委托对象调用方法
         nc1(25);
         Console.WriteLine("Value of Num: {0}", getNum());
         nc2(5);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces the following results:

Value of Num: 35
Value of Num: 175

Multicasting of delegates (Multicasting of a Delegate)

Delegate objects can be merged using the "plus" operator. A merged delegate calls the two delegates it merges. O nly the same type of delegates can be merged. T he "-" operator can be used to remove component delegates from merged delegates.

Using this useful feature of delegates, you can create a list of calls to methods that are called when delegates are called. T his is called multicasting, also known as multicasting. The following program demonstrates the multicasting of delegates:

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();
      }
   }
}

When the above code is compiled and executed, it produces the following results:

Value of Num: 75

The purpose of the delegate

The following example demonstrates the use of delegates. Delegate printString can be used to refer to a method with a string as input and does not return anything.

We use this delegate to call two methods, the first to print the string to the console and the second to print the string to the file:

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();
      }
   }
}

When the above code is compiled and executed, it produces the following results:

The String is: Hello World