News:

Choose a design and let our professionals help you build a successful website   - ITAcumens

Main Menu

Delegates and Events

Started by sukishan, Sep 04, 2009, 03:58 PM

Previous topic - Next topic

sukishan

Delegates and Events
Because the Java programming language has no built-in support for delegates and events, the J# implementation provides a set of extensions for creating this capability. Delegates are tagged with a special comment /** @delgate */ before its definition and so are events (using /** @event */). Also, the class implementing the events needs to keep a reference to all the listeners assigned for the particular events by creating an ArrayList or a similar collection. After the listeners have been assigned, they are invoked using the Invoke method .

package hks;
import System.*;
import System.Collections.*;

/** @delegate */
public delegate void EventHandler();

public class Button
{
  ArrayList listeners = new ArrayList();
  public static void main()
  {
    Button button = new Button();
    button.add_OnClick(new EventHandler(Button_OnClick));
    button.Click();
  }
  /** @event */
  public void add_OnClick(EventHandler listener) {
    listeners.Add(listener);
  }
  /** @event */
  public void remove_OnClick(EventHandler listener) {
    listeners.Remove(listener);
  }
  public void Click()
    {
     Object [] olisteners = listeners.ToArray();
    for (int i = 0;i < olisteners.length ;i++)
       {
         ((EventHandler)(olisteners)).Invoke();
       }
    }
  public static void Button_OnClick()
  {
    Console.WriteLine("Button Clicked");
  }
}/** @delegate */
public delegate void EventHandler
A good beginning makes a good ending