Code
// Copyright (c) Microsoft Corporation. All rights reserved.
// Events1.cs
Using system;
Namespace mycollections
{
Using system. collections;
// The delegate type used to hook the change notification.
Public Delegate void changedeventhandler (Object sender, eventargs E );
// A class, which is similar to arraylist,
// However, a notification is sent every time the list is changed.
Public class listwithchangedevent: arraylist
{
// An event. The client can use this event whenever the list element is changed.
// Get the notification.
Public event changedeventhandler changed;
// Call the changed event. It is called whenever the list is changed.
Protected virtual void onchanged (eventargs E)
{
If (changed! = NULL)
Changed (this, e );
}
// Rewrite some methods for changing the list;
// Call the event after each rewrite
Public override int add (object value)
{
Int I = base. Add (value );
Onchanged (eventargs. Empty );
Return I;
}
Public override void clear ()
{
Base. Clear ();
Onchanged (eventargs. Empty );
}
Public override object this [int Index]
{
Set
{
Base [Index] = value;
Onchanged (eventargs. Empty );
}
}
}
}
Namespace testeven TS
{
Using mycollections;
Class eventlistener
{
Private listwithchangedevent list;
Public eventlistener (listwithchangedevent List)
{
List = List;
// Add "listchanged" to the changed event in "list.
List. Changed + = new changedeventhandler (listchanged );
}
// The following call is performed whenever the list is changed.
Private void listchanged (Object sender, eventargs E)
{
Console. writeline ("this is called when the event fires .");
}
Public void detach ()
{
// Detach the event and delete the list
List. Changed-= new changedeventhandler (listchanged );
List = NULL;
}
}
Class Test
{
// Test the listwithchangedevent class.
Public static void main ()
{
// Create a new list.
Listwithchangedevent list = new listwithchangedevent ();
// Create a class to listen for the list change event.
Eventlistener listener = new eventlistener (list );
// Add and remove items in the list.
List. Add ("item 1 ");
List. Clear ();
Listener. Detach ();
Console. readkey ();
}
}
}