分享

C#的Event类. nodejs的Event风格

 勤奋不止 2017-07-17
[csharp] view plain copy
  1. //------------------------------------------------------------------------------  
  2. // <auto-generated>  
  3. //     This code was generated by a tool.  
  4. //     Runtime Version:4.0.30319.18408  
  5. //  
  6. //     Changes to this file may cause incorrect behavior and will be lost if  
  7. //     the code is regenerated.  
  8. // </auto-generated>  
  9. //------------------------------------------------------------------------------  
  10. using System;  
  11. using System.Collections.Generic;  
  12. using LitJson;  
  13.   
  14. namespace TSGame  
  15. {  
  16.     public class TSEvent  
  17.     {  
  18.         public delegate void EventHandler(JsonData data);  
  19.         static public TSEvent singleTon = new TSEvent();  
  20.   
  21.         public Dictionary<string, EventHandler> eventMap = new Dictionary<string, EventHandler>();  
  22.   
  23.         public TSEvent ()  
  24.         {  
  25.   
  26.         }  
  27.   
  28.         public void RegistEvent(string msg, EventHandler eh)  
  29.         {  
  30.             if (eventMap.ContainsKey(msg))  
  31.             {  
  32.                 eventMap[msg] += eh;  
  33.             }  
  34.             else  
  35.             {  
  36.                 eventMap.Add(msg, eh);  
  37.             }  
  38.         }  
  39.   
  40.         public void RemoveRegistEvent(string msg, EventHandler eh)  
  41.         {  
  42.             if (eventMap.ContainsKey(msg))  
  43.             {  
  44.                 eventMap[msg] -= eh;  
  45.             }  
  46.         }  
  47.   
  48.         public void SendMessage(string msg, JsonData json)  
  49.         {  
  50.             eventMap[msg].Invoke(json);  
  51.         }  
  52.     }  
  53. }  

用起来非常简单. 比方要监听回来的C_GetGW消息.那么就下面这写法.nodejs的 风格.

[csharp] view plain copy
  1. TSEvent.singleTon.RegistEvent("C_GetGW", 需要监听的函数);  

发消息就要 

[csharp] view plain copy
  1. TSEvent.singleTon.SendMessage("C_GetGW", JSON数据);  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多