2015-09-23

C# Event Handler Example

Program.cs

using System;

namespace EventHandlerTest
{
   class MainClass
   {
      public static void Main (string[] args)
      {
        //Account的money先給500
        Account myAccount = new Account (500);
        //加入Event發生後要執行的function
        myAccount.AlarmHandler += c_TriggerAlarmMessage;
        //提領超過200,會觸發事件
        myAccount.DrawMoney (300);
      }

      static void c_TriggerAlarmMessage(object sender, AlarmEventArgs e)
      {
        Console.WriteLine("The Alarm is trigger.");
        Environment.Exit(0);
      }
   }
}


Account.cs

using System;

namespace EventHandlerTest
{
 public class Account
 {
    public int totalMoney;

    //從帳戶提領錢
    public void DrawMoney(int money)
    {
      //超過200會觸發事件
      if (money > 200) {
        Trigger ();
      } else {
        totalMoney -= money;
      }
    }

    public Account (int totalMoney)
    {
       this.totalMoney = totalMoney;
    }


    public void Trigger()
    {
       AlarmEventArgs e = new AlarmEventArgs ();
       e.active = true;
       EventHandler handler = AlarmHandler;
       if (handler != null)
       {
         handler(this, e);
       }
    
    }

    public event EventHandler AlarmHandler;
  }
}


AlarmEventArgs.cs

using System;

namespace EventHandlerTest
{
   public class AlarmEventArgs
   {
     public AlarmEventArgs ()
     {
     }

     public bool active;
   }
}

No comments: