1. 程式人生 > >a sample of delegate & event

a sample of delegate & event


public delegate void NameListEventHandler(object sender, NameListEventArgs e);
public class NameListeventArgs:EventArgs
{
  string name;
  int count;
 
  public NameListArgs(string str, int i)
  {
    name = str;
    count = i;
  }

}

public class NameList
{
  ArrayList list;
  public event NameListEventHandler nameListEvent;

  public NameList()
  {
    list = new ArrayList();
  }

  public void Add(string Name)
  {
    list.Add(Name);
    if(nameListEvent != null)
    {
      nameListEvent(this, new NameListEventArgs(Name, list.Count));
    }
  }
}

public class EventDemo
{
   public static void main()
   {
     NameList names = new NameList();
     nameList.nameListEvent += new NameListEventHandler(NewName);

     names.Add("SMITH");
   }

   public static void NewName(object source, NameListEventArs args)
   {
     Console.WriteLine(args.Name+"was added to the list");
   }
}