为控件添加事件可以使用 += 的方法,同理移除事件可以使用 -= 。
问题来了,在不知道具体为了控件添加几次事件的情况下, -= 就无法知道要进行几次了,下面的方法可以解决这个问题。
方法一:用反射,反射是有缺点的,能不用就不用。
方法二:模仿.net维护事件表的机制,自己维护自己的事件表 。
下面以DataGridView控件的CellEnter事件 为例
EventHandlerList myEventHandlerList = new EventHandlerList(); //事件(委托)列表,记录事件 //添加DataGridView的CellEnter事件 void AddEvent(DataGridView control, DataGridViewCellEventHandler eventhandler) { control.CellEnter += eventhandler; myEventHandlerList.AddHandler(control, eventhandler); } //清除DataGridView的CellEnter事件 public void ClearEvent(DataGridView control) { Delegate d = myEventHandlerList[control]; foreach (Delegate dd in d.GetInvocationList()) control.CellEnter -= (DataGridViewCellEventHandler)dd; myEventHandlerList.RemoveHandler(control, d); }