委托和事件
作者:互联网
1、委托
namespace ConsoleApp1 { class Program { public delegate void Del(string message); static void Main(string[] args) { Del hanld = new Del(DelegateMethod); MethodWithCallback(1, 2, hanld); Console.Read(); } public static void DelegateMethod(string message) { Console.WriteLine(message); } public static void MethodWithCallback(int param1, int param2, Del callback) { callback(string.Format("当前的值为:{0}", (param1 + param2))); } } }
结果:
2、事件
namespace ConsoleApp1 { public class PublishEvent { public delegate void NoticeHandler(string message); public event NoticeHandler NoticeEvent; public void Works() { //触发事件 OnNoticed(); } protected virtual void OnNoticed() { if (NoticeEvent != null) { //传递事件及参数 NoticeEvent("Notice发布的报警信息!"); } } } public class SubscribEvent { public SubscribEvent(PublishEvent pub) { //订阅事件 pub.NoticeEvent += PrintResult; } /// <summary> /// 订阅事件后的响应函数 /// </summary> /// <param name="message"></param> void PrintResult(string message) { Console.WriteLine(string.Format("已收到{0}!采取措施!", message)); } } class Program { static void Main(string[] args) { PublishEvent publish = new PublishEvent(); SubscribEvent subscrib = new SubscribEvent(publish); //触发事件 publish.Works(); Console.Read(); } } }
结果:
借鉴:https://blog.csdn.net/qq_41872328/article/details/121333505
标签:Console,string,委托,NoticeEvent,void,事件,message,public 来源: https://www.cnblogs.com/chenze-Index/p/16473435.html