关于EventHandlerList的用法简介

来源:互联网 发布:vue.js事件对象event 编辑:程序博客网 时间:2024/05/17 08:15

EventHandlerList作为事件处理的替补方案

如果你发现你的服务组件对外需要提供很多的事件,而这些事件一般情况下你认为很少有程序拦截。使用EventHandlerList提供的功能将很适合你,如果使用.NET提供的默认事件机制,你可能在创建实例时消耗较多 的内存,而使用EventHandlerList挂接事件将节约内存。下面的代码演示了如何使用此功能。

private EventHandlerList _events = null;        /// <summary>        /// 供轻量级的事件对象        /// </summary>        protected new EventHandlerList Events {            get {                if (_events == null) {                    lock (this) {                        if (_events == null) {                            _events = new EventHandlerList();                        }                    }                }                return _events;            }        }        //事件key值        private static readonly object _startintEventKey = new object();        /// <summary>        /// Starting事件        /// </summary>        public event EventHandler Starting {            add {                this.Events.AddHandler(_startintEventKey, value);            }            remove {                this.Events.RemoveHandler(_startintEventKey, value);            }        }        /// <summary>        /// 引发事件Starting        /// </summary>        /// <param name="e"></param>        protected virtual void OnStarting(EventArgs e) {            this.RaiseEventByEventKey(_startintEventKey, e);        }        protected void RaiseEventByEventKey(object eventKey, EventArgs e){            if (eventKey == null)                throw new ArgumentNullException("eventKey");            if (_events != null) {                EventHandler handler = (EventHandler)_events[eventKey];                if (handler != null)                    handler(this, e);            }        }        public Form1() {            InitializeComponent();        }        private void Form1_Load(object sender, EventArgs e) {            this.Starting += new EventHandler(Form1_Starting);            this.OnStarting(EventArgs.Empty);        }        void Form1_Starting(object sender, EventArgs e) {            MessageBox.Show("test");        }


原创粉丝点击