1. Define the event parameter class first: EventArgs is the base class, it is not recommended to use it directly, because the generic thing is not strong and easy to confuse (especially when looking for bugs) ... MyEvent specific derived classes, the recommended way to use is to derive a class for each kind of event, such as Uievent,serverevent, which is named after the specific function.
[CSharp] View plain copy//<summary>///Event parameter base class///</summary> public class EventArgs { public object Parameter; }///<summary>//Custom event Parameters////</summary> public class Myevent:eventargs {public int ID ; public string Name; ... etc}
2. Event Management class: You can see that it is a singleton class that can be called directly around the world. _delegates is responsible for saving all the event receive methods, the event is in the type existence, the same type no matter how many records are only one item (so do not traverse the list of methods of the large string)
[CSharp] View Plain copy/// <summary> /// Event Management class /// </summary > public class eventmanager { //single case mode. public static readonly eventmanager instance = new eventmanager (); private eventmanager () { //Event delegation . public Delegate void eventdelegate<t> (t e) where T : EventArgs; //Save All events <span style= "Font-family:arial,helvetica,sans-serif" > How to receive </span>. readonly Dictionary<Type, Delegate> _delegates = new Dictionary<Type, Delegate> (); //Add an event receive method . public void AddListener<T> (eventdelegate<t > listener) where T : EventArgs { Delegate d; if (_delegates. TryGetValue (typeof (T), out d)) { _delegates[typeof (T)] = delegate.combine (d, listener); } else { _delegates[ typeof (T)] = listener; } } //Delete an event acceptance method public void RemoveListener<T> (Eventdelegate<t> listener) where T : EventArgs