As already mentioned about the design ideas now beginning to implement an event system. The so-called event system, in fact, is a collection of events. The event storing a unified management.
Event is one to many relationship, and I chose to represent a string events. HashSet used to store multiple delegate. That this Key / Value collection of natural selection dictionaries storage. Here we have not discussed the specific design commission. Let EventMethod with a class to represent.
Implement the following code.
/// <summary> /// 事件系统 /// </summary> public class EventSystem { #region Field /// <summary> /// 事件容器 /// </summary> private readonly Dictionary<string, HashSet<EventMethod>> events = new Dictionary<string, HashSet<EventMethod>>(); #endregion #region Method /// <summary> /// 添加事件 /// </summary> /// <param name = "EventMethod"> </ param> public BOOL the Add (EventMethod EventMethod) { // event in the set of methods that may be present is determined immediately, but is immediately deleted in another thread. So here 5 retries for ( int = I 0 ; I < . 5 ; I ++ ) { // create a set of methods event IF (! ) events.ContainsKey (eventMethod.Handle) { Lock (events) { IF (! ) events.ContainsKey (eventMethod.Handle) events.Add (eventMethod.Handle, new new HashSet <EventMethod> ()); } } // add an event to the collection method of IF (events.TryGetValue (eventMethod.Handle, OUT var hashSet)) return hashSet.Add (EventMethod); } return to false ; // the throw new new Exception ($ "Add Event {eventMethod.Handle failed}! "); } /// <Summary> /// removal event /// </ Summary> /// <param name =" EventMethod "> </ param> public void the remove (EventMethod EventMethod) { IF (events.TryGetValue (eventMethod.Handle,out was hashSet)) { hashSet.Remove (EventMethod); // remove event collection method has been vacant IF (hashSet.Count <= 0 ) events.Remove (eventMethod.Handle); } } #endregion }
EventMethod There is a property Hnadle he was commissioned to represent the kind of event so when added to implement the system adds it to the collection method corresponding event. Similarly removed.
A simple event container on the design better. Of course, now can not trigger, we design a good EventMethod after the trigger can be filled in. Back began to implement the event.
Portal: