如何:使用字典儲存事件執行個體(C# 編程指南)

來源:互聯網
上載者:User

 

C# 編程指南 如何:使用字典儲存事件執行個體(C# 編程指南)  accessor-declarations 的一種用法是公開大量的事件但不為每個事件分配欄位,而是使用字典來儲存這些事件執行個體。這隻有在具有非常多的事件、但您預計大部分事件都不會實現時才有用。 樣本C#複製代碼public delegate void EventHandler1(int i);public delegate void EventHandler2(string s); publicclass 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        {            eventTable["Event1"] = (EventHandler1)eventTable["Event1"] + value;        }        remove        {            eventTable["Event1"] = (EventHandler1)eventTable["Event1"] - value;        }    }     public event EventHandler2 Event2    {        add        {            eventTable["Event2"] = (EventHandler2)eventTable["Event2"] + value;        }        remove        {            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);        }    }} publicclass TestClass{    publicstaticvoid Delegate1Method(int i)    {        System.Console.WriteLine(i);    }     publicstaticvoid Delegate2Method(string s)    {        System.Console.WriteLine(s);    }     staticvoid 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");    }} 輸出2TestString  (來源:msdn ) 
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.