事件实现简洁版:
public event EventHandler<MailEventArgs> NewMail; protected virtual void OnNewMail(MailEventArgs e) { EventHandler<MailEventArgs> temp = Interlocked.CompareExchange(ref NewMail, null, null); if (temp != null) { temp(this, e); } } public void SimulateNewMail(String from, String to, String subject) { MailEventArgs e = new MailEventArgs(from, to, subject); OnNewMail(e); }
事件注册:
多个事件实现:
public sealed class EventSet { // The private dictionary used to maintain EventKey -> Delegate mappings private readonly Dictionary<EventKey, Delegate> m_events = new Dictionary<EventKey, Delegate>(); // Adds an EventKey -> Delegate mapping if it doesn't exist or // combines a delegate to an existing EventKey public void Add(EventKey eventKey, Delegate handler) { Monitor.Enter(m_events); Delegate d; m_events.TryGetValue(eventKey, out d); m_events[eventKey] = Delegate.Combine(d, handler); Monitor.Exit(m_events); } // Removes a delegate from an EventKey (if it exists) and // removes the EventKey -> Delegate mapping the last delegate is removed public void Remove(EventKey eventKey, Delegate handler) { Monitor.Enter(m_events); // Call TryGetValue to ensure that an exception is not thrown if // attempting to remove a delegate from an EventKey not in the set Delegate d; if (m_events.TryGetValue(eventKey, out d)) { d = Delegate.Remove(d, handler); // If a delegate remains, set the new head else remove the EventKey if (d != null) m_events[eventKey] = d; else m_events.Remove(eventKey); } Monitor.Exit(m_events); } // Raises the event for the indicated EventKey public void Raise(EventKey eventKey, Object sender, EventArgs e) { Delegate d; Monitor.Enter(m_events); m_events.TryGetValue(eventKey, out d); Monitor.Exit(m_events); if (d != null) { d.DynamicInvoke(new Object[] { sender, e }); } } }