[记]C#的委托和事件
一、委托
委托的关键字是delegate;
声明委托:
public delegate void printString(string s);
委托的传入参数是 string,但是在实际使用时是传入函数方法;
static void Main(string[] args) { // printString ps; printString ps1 = new printString(WriteToScreen); printString ps2 = new printString(WriteToFile); // ps=ps1; ps1+=ps2; ps1("hhello"); Console.ReadKey(); }
实例化的委托以方法传入,每个方法的传入参数需与委托的定义参数一致;
当使用+=运算符将多个实例化委托添加到ps1时,只需要调用ps1即可同时对多个委托进行处理;

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("d:\\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"); ps("time--"); } static void Main(string[] args) { // printString ps; printString ps1 = new printString(WriteToScreen); printString ps2 = new printString(WriteToFile); // ps=ps1; ps1+=ps2; sendString(ps1); Console.ReadKey(); } } }
二、事件
事件常和委托一起使用;
在定义委托后才能定义调用委托的事件;
public delegate void NumManipulationHandler(int num); public event NumManipulationHandler ChangeNum;
事件可以添加多个委托,当事件触发时,多个委托方法也同时调用;
public static void Main() { EventTest e = new EventTest(); /* 实例化对象,第一次没有触发事件 */ MainClass pp = new MainClass(); e.ChangeNum += new EventTest.NumManipulationHandler(pp.printf); /* 注册 */ e.SetValue( 7 ); e.SetValue( 11 ); }
激活事件则是通过调用事件函数,给事件名后面添加小括号;

using System; namespace SimpleEvent { using System; public class EventTest { private int value; public delegate void NumManipulationHandler(int num); public event NumManipulationHandler ChangeNum; public EventTest() { int n = 5; SetValue( n ); } public void SetValue( int n ) { if ( value != n ) { value = n; if(ChangeNum!=null){ ChangeNum(n); } } } } public class MainClass { public void printf(int num) { Console.WriteLine(num.ToString()); Console.WriteLine( "event fire" ); Console.ReadKey(); /* 回车继续 */ } public static void Main() { EventTest e = new EventTest(); /* 实例化对象,第一次没有触发事件 */ MainClass pp = new MainClass(); e.ChangeNum += new EventTest.NumManipulationHandler(pp.printf); /* 注册 */ e.SetValue( 7 ); e.SetValue( 11 ); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?