🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 如何:使用字典存储事件实例(C# 编程指南) **accessor-declarations** 的一种用法是公开很多事件但不为每个事件分配字段,而是使用字典来存储这些事件实例。这只在具有很多事件但您预计大多数事件都不会实现时才有用。 ``` public delegate void EventHandler1(int i); public delegate void EventHandler2(string s); public class PropertyEventsSample { private System.Collections.Generic.Dictionary<string, System.Delegate> eventTable; public PropertyEventsSample() { eventTable = new System.Collections.Generic.Dictionary<string, System.Delegate>(); eventTable.Add("Event1", null); eventTable.Add("Event2", null); } public event EventHandler1 Event1 { add { lock (eventTable) { eventTable["Event1"] = (EventHandler1)eventTable["Event1"] + value; } } remove { lock (eventTable) { eventTable["Event1"] = (EventHandler1)eventTable["Event1"] - value; } } } public event EventHandler2 Event2 { add { lock (eventTable) { eventTable["Event2"] = (EventHandler2)eventTable["Event2"] + value; } } remove { lock (eventTable) { eventTable["Event2"] = (EventHandler2)eventTable["Event2"] - value; } } } internal void RaiseEvent1(int i) { EventHandler1 handler1; if (null != (handler1 = (EventHandler1)eventTable["Event1"])) { handler1(i); } } internal void RaiseEvent2(string s) { EventHandler2 handler2; if (null != (handler2 = (EventHandler2)eventTable["Event2"])) { handler2(s); } } } public class TestClass { public static void Delegate1Method(int i) { System.Console.WriteLine(i); } public static void Delegate2Method(string s) { System.Console.WriteLine(s); } static void Main() { PropertyEventsSample p = new PropertyEventsSample(); p.Event1 += new EventHandler1(TestClass.Delegate1Method); p.Event1 += new EventHandler1(TestClass.Delegate1Method); p.Event1 -= new EventHandler1(TestClass.Delegate1Method); p.RaiseEvent1(2); p.Event2 += new EventHandler2(TestClass.Delegate2Method); p.Event2 += new EventHandler2(TestClass.Delegate2Method); p.Event2 -= new EventHandler2(TestClass.Delegate2Method); p.RaiseEvent2("TestString"); // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } } /* Output: 2 TestString */ ``` ## 请参阅 [C# 编程指南](https://msdn.microsoft.com/zh-cn/library/67ef8sbd.aspx) [事件(C# 编程指南)](https://msdn.microsoft.com/zh-cn/library/awbftdfh.aspx) [委托(C# 编程指南)](https://msdn.microsoft.com/zh-cn/library/ms173171.aspx)