
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
276
|
Chapter 4: Generics
{
private List<T> _items = new List<T>( );
// Private method that will dispose of items in the list
private void Delete(T item)
{
item.Dispose( );
}
This DisposableList class allows only an object that implements IDisposable to be
passed in as a type argument to this class. The reason for this is that whenever an
object is removed from a
DisposableList object, the Dispose method is always called
on that object. This allows you to transparently handle the management of any
object stored within this
DisposableList object.
The following code exercises a
DisposableList object:
public static void TestDisposableListCls( )
{
DisposableList<StreamReader> dl = new DisposableList<StreamReader>( );
// Create a few test objects.
StreamReader tr1 = new StreamReader("c:\\boot.ini");
StreamReader tr2 = new StreamReader("c:\\autoexec.bat");
StreamReader tr3 = new StreamReader("c:\\config.sys");
// Add the test object to the DisposableList.
dl.Add(tr1);
dl.Insert(0, tr2);
dl.Add(tr3);
foreach(StreamReader sr in dl)
{
Console.WriteLine("sr.ReadLine( ) == " + sr.ReadLine( ));
}
// Call Dispose before any of the disposable objects are
// removed from the DisposableList.
dl.RemoveAt(0);
dl.Remove(tr1);
dl.Clear( );
}
Discussion
The where keyword is used to constrain a type parameter ...