protected virtual void OnThresholdReached(ThresholdReachedEventArgs e) { EventHandler <ThresholdReachedEventArgs> handler = ThresholdReached_delegate; if (handler != null) { handler(this, e); } else { Console.WriteLine("Hmmm OnThreshold does not appear to have a handler yet"); } }
public void Eat(int x) { totalEaten += CalculateFoodSize(x); if (totalEaten > foodTillFull) { ThresholdReachedEventArgs args = new ThresholdReachedEventArgs(totalEaten, DateTime.Now); OnThresholdReached(args); } else { ConditionFailedEventArgs args = new ConditionFailedEventArgs(DateTime.Now); OnConditionFailed(args); } }
//Here I actually create the handlers. In the namespace,(EventTypes.cs) resides the event arg data structures //Foody can raise a ThresholdReached event if the stomach is full, so inside of Foody one must create two things //1. The EventHandler delegate that eventually stores a reference of our handling method //2. The OnEvent virtual which then checks to see if the delegate has a valid reference, if it does, then it calls this method //I then create the handlers outside the context of the class, passing in a context reference "object sender" //where sender is the object that raises the event, in this case some instance of Foody static void HandleThresholdReached(object sender, ThresholdReachedEventArgs e) { Console.WriteLine("Handling threshold reached: size {0} at {1}", e.Size, e.TimeReached); }