事件访问器2007-09-24 本站 如Button的例子所示,大多数情况下事件的声明都省略了事件访问声明。什么情况下使用事件访问声明呢?答案是:如果每个事件的存储开销太大,我们就可以在类中包含事件访问声明,按私有成员的规则存入事件句柄列表。访问器的声明包括两种:添加访问器声明(add-accessor-declaration)和删除访问器声明(remove-accessor-declaration)。访问器声明之后跟随相关执行代码的语句块。在添加访问器声明后的代码需要执行添加事件句柄的操作,在删除访问器声明后的代码需要执行删除事件句柄的操作。不管是哪种事件访问器,都对应相应的一个方法,这个方法只有一个事件类型的值参数,并且返回值为void。在执行预订操作时使用添加型访问器,在执行撤消操作时使用删除型访问器。访问器中实际上还包含了一个名为value的隐藏的参数,因而访问器在使用局部变量时不能再使用这个名字。下面给出了使用访问器的例子。程序清单13-3:
class Control:Component{ //Unique keys for events static readonly object mouseDownEventKey=new object(); static readonly object mouseUpEventKey=new object(); //Return event handler associated with key protected Delegate GetEventHandler(object key){...} //Add event handler associated with key protected void AddEventHandler(object key,Delegate handler){...} //Remove event handler associated with key protected void RemoveEventHandler(object key,Delegate handler){...} //MouseDown event public event MouseEventHandler MouseDown{add{AddEventHandler(mouseDownEventKey,value);}remove{AddEventHandler(mouseDownEventKey,value);} } //MouseUp event public event MouseEventHandler MouseUp{add{AddEventHandler(mouseUpEventKey,value);}remove{AddEventHandler(mouseUpEventKey,value);} }}