数据字典存储事件实例

      当有很多事件,大多数事件不会实现时,可以使用字典存储事件实例,这也是事件选择器的典型用法。

    public delegate void EventHandler1(int i);

    public delegate void EventHandler2(string s);



    public class PropertyEvent

    {

        Dictionary<string, System.Delegate> eventTable;



        public PropertyEvent()

        {

            eventTable = new Dictionary<string, 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;

                }

            }

        }



        public void RaiseEvent1(int i)

        {

            EventHandler1 handler1 = (EventHandler1)eventTable["Event1"];

            if (handler1 != null)

                handler1(i);

        }



        public void RaiseEvent2(string s)

        {

            EventHandler2 handler2 = (EventHandler2)eventTable["Event2"];

            if (handler2 != null)

                handler2(s);

        }

    }



    class DictionaryEvent

    {

        public static void DelegateMethod1(int i)

        {

            Console.WriteLine(i.ToString());

        }

        public static void DelegateMethod2(string s)

        {

            Console.WriteLine(s);

        }

        public static void Main(string[] args)

        {

            PropertyEvent p = new PropertyEvent();



            p.Event1 += DictionaryEvent.DelegateMethod1;

            p.Event1 += DictionaryEvent.DelegateMethod1;

            p.Event1 += DictionaryEvent.DelegateMethod1;

            p.Event1 -= DictionaryEvent.DelegateMethod1;

            p.RaiseEvent1(1);



            p.Event2 += DictionaryEvent.DelegateMethod2;

            p.Event2 += DictionaryEvent.DelegateMethod2;

            p.Event2 += DictionaryEvent.DelegateMethod2;

            p.Event2 -= DictionaryEvent.DelegateMethod2;

            p.RaiseEvent2("Test");



            Console.Read();

        }

    }

输出如下:

你可能感兴趣的:(数据字典)