程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 事件訪問器

事件訪問器

編輯:關於C語言

如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);}
 }
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved