
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
146
|
Chapter 3: Classes and Structures
public class Personnel<T> : List<T>, IPrint
{
public void Print( )
{
foreach (T obj in this)
{
Console.WriteLine("Person: " + obj);
}
}
}
The following two methods, TestIPrintInterface and CommonPrintMethod, show how
any object that implements the IPrint interface can be passed to the CommonPrintMethod
polymorphically and printed:
public void TestIPrintInterface( )
{
// Create an InventoryItems object and populate it.
IPrint obj = new InventoryItems<string>( );
((InventoryItems<string>)obj).Add("Item1");
((InventoryItems<string>)obj).Add("Item2");
// Print this object.
CommonPrintMethod(obj);
Console.WriteLine( );
// Create a Personnel object and populate it.
obj = new Personnel<string>( );
((Personnel<string>)obj).Add("Person1");
((Personnel<string>)obj).Add("Person2");
// Print this object.
CommonPrintMethod(obj);
}
private void CommonPrintMethod(IPrint obj)
{
Console.WriteLine(obj.ToString( ));
obj.Print( );
}
The output of these methods is shown here:
CSharpRecipes.ClassAndStructs+InventoryItems`1[System.String]
Inventory Item: Item1
Inventory Item: Item2
CSharpRecipes.ClassAndStructs+Personnel`1[System.String]
Person: Person1
Person: Person2
Discussion
The use of interfaces is found throughout the FCL. One example is the IComparer
interface: this ...