Home   Cover Cover Cover Cover
 

Trigger

A02.cs
using System;

delegate bool Condition(object obj);
delegate void Action(object obj);

//----- Counter ------
class Counter {
  int val = 0;
  
  public event Condition cond;
  public event Action fire;
  
  public int Value { get { return val; } }
  
  public void Add(int x) {
    val += x; Check();
  }
  
  public void Clear() {
    val = 0; Check();
  }
  
  void Check() {
    if (cond != null && fire != null && cond(this)) fire(this);
  }
}

//----- Test of Counter -----

class Test {
  static int holdValue = 0;
  
  // trigger an action if the counter value is greater than 100
  static bool CheckLimit(object ctr) {
    return (((Counter)ctr).Value > 100);
  }
  
  // print an overflow warning
  static void Alarm(object ctr) {
    Console.WriteLine("- counter overflow");
  }
  
  // capture the old counter value and reset the counter
  static void Reset(object ctr) {
    holdValue = ((Counter)ctr).Value;
    Console.WriteLine("holdValue = " + holdValue);
    ((Counter)ctr).Clear();
  }
  
  public static void Main() {
    Counter counter = new Counter();
    counter.cond += new Condition(CheckLimit);
    counter.fire += new Action(Alarm);
    counter.fire += new Action(Reset);
    
    counter.Add(70);
    counter.Add(40);
    counter.Add(25);
    counter.Add(60);
    counter.Add(20);
  }
}