C#的事件,就是定义一个委托事件,事件就是一个委托,然后定义一个触发方法,将你需要激活的事件放入委托事件中,然后调用触发方法,就可以激活事件
事列代码
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Web.Script.Serialization; namespace ConsoleApp1 { public class Program { //自定义委托 public delegate void MarryHandler(string msg); //使用自定义委托类型定义事件,事件名为MarrEvent public event MarryHandler MarrayEvent; static void Main(string[] args) { //初始化新郎官对象 Program bridegroom = new Program(); //实例化朋友对象 Friend friend1 = new Friend("张三"); Friend friend2 = new Friend("李四"); Friend friend3 = new Friend("王五"); //使用"+="订阅消息 bridegroom.MarrayEvent += new MarryHandler(friend1.SendMessage); bridegroom.MarrayEvent += new MarryHandler(friend2.SendMessage); //使用"-="取消消息 bridegroom.MarrayEvent -= new MarryHandler(friend2.SendMessage); //发出通知 bridegroom.OnMarriageComing("到时来参见婚礼!"); Console.ReadLine(); //输出结果为 //到时来参加婚礼! //张三收到了,到时候来参加 } public void OnMarriageComing(string msg) { //判断是否绑定了事件处理方法 if (MarrayEvent != null) { //触发事件 MarrayEvent(msg); } } } //朋友类 public class Friend { //字段 public string Name; //构造函数 public Friend(string name) { Name = name; } //事件处理函数,该函数符合MarryHandler委托的定义 public void SendMessage(string mssage) { //输出通知消息 Console.WriteLine(mssage); //对事件做出处理 Console.WriteLine(this.Name + "收到了,到时候来参加"); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Web.Script.Serialization; namespace ConsoleApp1 { public class Program { //自定义委托 public delegate void MarryHandler(object sender, MarryEventArgs e); //使用自定义委托类型定义事件,事件名为MarrEvent public event MarryHandler MarrayEvent; static void Main(string[] args) { //初始化新郎官对象 Program bridegroom = new Program(); //实例化朋友对象 Friend friend1 = new Friend("张三"); Friend friend2 = new Friend("李四"); Friend friend3 = new Friend("王五"); //使用"+="订阅消息 bridegroom.MarrayEvent += new MarryHandler(friend1.SendMessage); bridegroom.MarrayEvent += new MarryHandler(friend2.SendMessage); //使用"-="取消消息 bridegroom.MarrayEvent -= new MarryHandler(friend2.SendMessage); //发出通知 bridegroom.OnMarriageComing("到时来参见婚礼!"); Console.ReadLine(); //输出结果为 //到时来参加婚礼! //张三收到了,到时候来参加 } //发出事件 public void OnMarriageComing(string msg) { //判断是否绑定了事件处理方法 if (MarrayEvent != null) { //触发事件 MarrayEvent(this, new MarryEventArgs(msg)); } } } //朋友类 public class Friend { //字段 public string Name; //构造函数 public Friend(string name) { Name = name; } //事件处理函数,该函数符合MarryHandler委托的定义 public void SendMessage(object s, MarryEventArgs e) { //输出通知消息 Console.WriteLine(e.Message); //对事件做出处理 Console.WriteLine(this.Name + "收到了,到时候来参加"); } } //自定义事件类,并使其带有事件数据 public class MarryEventArgs : EventArgs { public string Message; public MarryEventArgs(string msg) { Message = msg; } } }