[C#語法] 事件(Event)使用簡單三步| 誠的碼記本 - - 點部落

文章推薦指數: 80 %
投票人數:10人

用C#自訂事件簡單作法. ... 委派 delegate void EventPrototype(object sender, EventArgs e); //宣告事件 public event EventPrototype eventName; }. 用C#自訂事件簡單作法 (1)在自訂類別中宣告委派與事件 publicclassClassName { //宣告委派 delegatevoidEventPrototype(objectsender,EventArgse); //宣告事件 publiceventEventPrototypeeventName; } (2)設定事件觸發位置 publicclassClassName { //宣告委派 delegatevoidEventPrototype(objectsender,EventArgse); //宣告事件 publiceventEventPrototypeeventName; //自訂方法 voidfunction(){ //宣告objectType變數 objectobj=newobject(); //在類別中未註冊事件時,可避免觸發時的null錯誤 //事件名稱?.Invoke(事件參數); eventName?.Invoke(obj,newEventArgs()); } } (3)在實際使用class中註冊事件 //實體化類別 ClassNameobj=newClassName(); //註冊事件,定義當事件觸發時要處裡事件的函式 obj.eventName+=newClassName.EventPrototype(functionName); privatevoidfunctionName(objectsender,EventArgse) { //當觸發事件時要處理的函式 }   C# 回首頁



請為這篇文章評分?