C# - 委托语句

C# - 委托语句 首页 / C#入门教程 / C# - 委托语句

C#委托类似于 C 或C+中指向函数的指针,委托是保存对方法的引用类型变量,可以在运行时更改引用。

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

声明委托

委托声明确定委托可以引用的方法,委托可以引用与委托具有相同签名的方法。

public delegate int MyDelegate (string s);

前面的委托可用于引用具有单个string参数并返回int类型变量的任何方法。

委托声明的语法为-

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

下面的示例演示了委托的声明、实例化和使用该委托可用于引用接受整数参数并返回整数值的方法。

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) {
         //create delegate instances
         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();
      }
   }
}

编译并执行上述代码时,将生成以下输出-

Value of Num: 35
Value of Num: 175

委托组播

可以使用“ +”运算符来组成委托对象,只能组成相同类型的代表。“-”运算符可用于从组合委托中删除组件委托。

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) {
         //create delegate instances
         NumberChanger nc;
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);
         
         nc = nc1;
         nc += nc2;
         
         //calling multicast
         nc(5);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}

编译并执行上述代码时,将生成以下输出-

Value of Num: 75

使用委托

下面的示例演示了委托的用法,委托printString可用于引用接受字符串作为输入但不返回任何内容的方法。

无涯教程使用此委托调用两个方法,第一个方法将字符串打印到控制台,第二个方法将其打印到文件-

using System;
using System.IO;

namespace DelegateAppl {

   class PrintString {
      static FileStream fs;
      static StreamWriter sw;
      
      //delegate declaration
      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();
      }
   }
}

编译并执行上述代码时,将生成以下输出-

The String is: Hello World

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

苏杰的产品创新课 -〔苏杰〕

Linux内核技术实战课 -〔邵亚方〕

恋爱必修课 -〔李一帆〕

Go 语言项目开发实战 -〔孔令飞〕

超级访谈:对话汤峥嵘 -〔汤峥嵘〕

徐昊 · TDD项目实战70讲 -〔徐昊〕

快手 · 音视频技术入门课 -〔刘歧〕

Web 3.0入局攻略 -〔郭大治〕

Dubbo源码剖析与实战 -〔何辉〕

好记忆不如烂笔头。留下您的足迹吧 :)