在C#應用字典存儲事宜示例及完成自界說事宜拜訪器。本站提示廣大學習愛好者:(在C#應用字典存儲事宜示例及完成自界說事宜拜訪器)文章只能為提供參考,不一定能成為您想要的結果。以下是在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(); } }
輸入:
2 TestString
完成自界說事宜拜訪器
事宜是特別類型的多路播送拜托,只能從聲明它的類中挪用。客戶端代碼經由過程供給對應在激發事宜時挪用的辦法的援用來定閱事宜。這些辦法經由過程事宜拜訪器添加到拜托的挪用列表中,事宜拜訪器相似於屬性拜訪器,分歧的地方在於事宜拜訪器被定名為 add 和 remove。在年夜多半情形下都不須要供給自界說的事宜拜訪器。假如您在代碼中沒有供給自界說的事宜拜訪器,編譯器會主動添加事宜拜訪器。但在某些情形下,您能夠須要供給自界說行動。上面的示例演示若何完成自界說的 add 和 remove 事宜拜訪器。固然可以調換這些拜訪器內的任何代碼,但建議您在添加或移除新的事宜處置法式辦法之前先鎖定該事宜。
event EventHandler IDrawingObject.OnDraw { add { lock (PreDrawEvent) { PreDrawEvent += value; } } remove { lock (PreDrawEvent) { PreDrawEvent -= value; } } }