C# Tutoriallogin
C# Tutorial
author:php.cn  update time:2022-04-11 14:06:23

C# Delegate



#A delegate in C# is similar to a pointer to a function in C or C++. Delegate is a reference type variable that holds a reference to a method. References can be changed at runtime.

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

Declaration of Delegate (Delegate)

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

For example, suppose there is a delegate:

public delegate int MyDelegate (string s);

The above delegate can be used to reference any method that takes a single string parameter and returns a int type variable.

The syntax for declaring a delegate is as follows:

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

Instancing the delegate (Delegate)

Once the delegate type is declared, the delegate object must use the new keyword to be created and associated with a specific method. When creating a delegate, the parameters passed to the new statement are written like a method call, 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, which can be used to reference 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 will produce the following results:

Value of Num: 35
Value of Num: 175

Multicasting of a Delegate

The delegate object can be used "+" operator for merging. A merged delegate calls the two delegates it merges. Only delegates of the same type can be merged. The "-" operator can be used to remove component delegates from merged delegates.

Using this useful feature of delegates, you can create a call list of methods to be called when the delegate is called. This is called delegated multicasting, also called multicast. The following program demonstrates delegated 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();
      }
   }
}

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

Value of Num: 75

Purpose of Delegate

The following example demonstrates the use of delegation. The delegate printString can be used to reference a method that takes a string as input and does not return anything.

We use this delegate to call two methods, the first prints the string to the console, the second prints 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 when executed, it produces the following results:

The String is: Hello World

php.cn