//首先是指代的聲明,它定義了喚醒某個函數的事件信號 public delegate void ScoreChangeEventHandler (int newScore, ref bool cancel);
//定義一個產生事件的類 > public class Game { // 注意這裡使用了event關鍵字 public event ScoreChangeEventHandler ScoreChange; int score; // Score 屬性 public int Score { get { return score; } set { if (score != value) { bool cancel = false; ScoreChange (value, ref cancel); if (! cancel) score = value; } } }
// 處理事件的類 public class Referee { public Referee (Game game) { // 裁判負責調整比賽中的分數變化 game.ScoreChange += new ScoreChangeEventHandler (game_ScoreChange); }
// 注意這裡的函數是怎樣和ScoreChangeEventHandler的信號對上號的 private void game_ScoreChange (int newScore, ref bool cancel) { if (newScore $#@60; 100) System.Console.WriteLine ("Good Score"); else { cancel = true; System.Console.WriteLine ("No Score can be that high!"); } } }
// 主函數類,用於測試上述特性 public class GameTest { public static void Main () { Game game = new Game (); Referee referee = new Referee (game); game.Score = 70; game.Score = 110; } }