2016年7月24日 星期日

C# Delegate and Event 委派和事件(二)

這一篇會用到我們上篇所學到的,寫出一個符合完整.Net Framework規範的範例。


範例說明:
假設我們有一個氣象站,當這個氣象站(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();
}


沒有留言:

張貼留言