C#使用事件

using System;
namespace MyCollections
{
   using System.Collections;

   public delegate void ChangedEventHandler(object sender, EventArgs e);
   public class ListWithChangedEvent: ArrayList
   {
       public event ChangedEventHandler MyAdd;

       public event ChangedEventHandler MyClear;
      protected virtual void OnAdd(EventArgs e)
      {
          if (MyAdd != null)
              MyAdd(this, e);
      }
       protected virtual void OnClear(EventArgs e)
       {
           if (MyClear != null)
               MyClear(this, e);
       }

      public override int Add(object value)
      {
         int i = base.Add(value);
         OnAdd(EventArgs.Empty);
         return i;
      }

      public override void Clear()
      {
         base.Clear();
         OnClear(EventArgs.Empty);
      }
   }

   class Test
   {

      // This will be called whenever the list changes.
      public static void AddChanged(object sender, EventArgs e)
      {
         Console.WriteLine("This is called when the event fires.    Add");
      }

       public static void ClearChanged(object sender, EventArgs e)
       {
           Console.WriteLine("This is called when the event fires. Clear");
       }
      public static void Main()
      {
       ListWithChangedEvent list = new ListWithChangedEvent();
       list.MyAdd += new ChangedEventHandler(AddChanged);
       list.MyAdd += new ChangedEventHandler(AddChanged);
       list.MyClear += new ChangedEventHandler(ClearChanged);
       list.Add("item 1");
       list.Clear();
       list.Add("item 1");
       list.Clear();
    
      }
   }
}

posted on 2010-03-29 18:18  一路前行  阅读(200)  评论(0编辑  收藏  举报