範例說明:
假設我們有一個氣象站,當這個氣象站(weatherStation)溫度超過35度時,會通知氣象站網頁(weatherWeb),氣象站網頁會顯示出氣象站名稱,與溫度。
public class WeatherStation { public string StationName { get; set; } private int Temperature { get; set; } public delegate void NotifyEventHandler(Object sender, WeatherDataEventArgs e); public event NotifyEventHandler Notify; public void UpdateData() { for (int i = 0; i < 120; i++) { Temperature = i; if (Temperature > 35) { WeatherDataEventArgs e = new WeatherDataEventArgs(Temperature); if (Notify != null) Notify(this, e); } } } } public class WeatherWeb { public void ShowData(Object sender, WeatherDataEventArgs e) { Console.WriteLine(((WeatherStation)sender).StationName + " " + e.Temperature); } } public class WeatherDataEventArgs : EventArgs { public int Temperature { get; set; } public WeatherDataEventArgs(int temperature) { this.Temperature = temperature; } }
public static void Main(string[] args) { WeatherStation station = new WeatherStation(); station.Notify += new WeatherWeb().ShowData; station.UpdateData(); }
沒有留言:
張貼留言