简单理解C#委托事件,示例如下所示:
using System; /// <summary> /// ---------------------委托步骤--------------------- /// 第一步:声明委托 /// 第二步:委托使用方法的实现 /// 第三步:委托的解释(将方法以变量的形式传递,且以方法的形式执行)--方法与委托建立联系 /// 注: /// 委托链的概念(+=、-=,+=表示建立联系,-=表示委托作废) /// 匿名函数:一次性调用(如需多次调用,则应提取) /// /// ---------------------事件:可理解为一种特殊的功能受限的委托--------------------- /// 第一步:声明事件(eg:public static event DelegateSayHello EventSayHello;) /// 第二步:订阅或取消事件(+=/-=) /// 第三步:调用事件 /// </summary> namespace DelegateDemo { /// <summary> /// 无参无返回值委托 /// </summary> public delegate void DelegateSayHello(); /// <summary> /// 带参无返回值委托 /// </summary> /// <param name="messageInfo">参数信息</param> /// <returns></returns> public delegate string DelegateSayMessage(string messageInfo); /// <summary> /// 带参无返回值委托 /// </summary> /// <param name="messageInfo">参数信息</param> public delegate void DelegateSayGoodBye(string messageInfo); class Program { //声明事件 public static event DelegateSayMessage EventSayHello; static void Main(string[] args) { string message = DelegateTest(); //Console.WriteLine(message); //注册事件/订阅事件 EventSayHello += Program_EventSayMessage; //调用事件 if (EventSayHello != null) Program_EventSayMessage("事件调用来一波"); Console.ReadLine(); } private static string Program_EventSayMessage(string messageInfo) { Console.WriteLine($"{messageInfo}"); return messageInfo; } private static string DelegateTest() { //委托简单用法 DelegateSayHello say = SayHello; say(); DelegateSayMessage mes = SayMessage; string message = mes("带参带返回值"); //委托链用法 DelegateSayHello say1 = SayHello; say += SayHello; say -= SayHello; //匿名函数用法 DelegateSayGoodBye nickMethod = delegate (string messageInfo) { Console.WriteLine($"{messageInfo}我是无参无返回值匿名函数"); }; nickMethod("nickMethod 匿名方法调用=="); DelegateSayMessage returnSay = delegate (string messageInfo) { string str = messageInfo + "有参有返回值匿名函数:"; Console.WriteLine(str); return str; }; returnSay("returnSay 匿名方法调用=="); //Lamda表达式 DelegateSayGoodBye lamda = (messageInfo) => { Console.WriteLine($"{messageInfo }lamda用法来一波"); }; lamda("swg:"); return message; } private static void SayHello() { Console.WriteLine("hello delegate"); } private static string SayMessage(string messageInfo) { string str = "SayMessage==" + messageInfo; return str; } } }
标签:Console,string,委托,C#,简介,messageInfo,static,delegate From: https://www.cnblogs.com/YYkun/p/17023073.html