This article is based on the book Accelarated C #2008.
Using System;
Using System. Collections. Generic;
Public interface IShape
{
Double Area
{
Get;
}
}
Public class Circle: Ishape
{
Public Circle (double radius)
{
This. radius = radius;
}
Public double Area
{
Get
{
Return 3.1415 * radius
}
}
Private double radius;
}
Public class Rect: IShape
{
Public Rect (double width, double height)
{
This. width = width;
This. height = height;
}
Public double Area
{
Get
{
Return width * height;
}
}
Private double width;
Private double height;
}
Public class Shapes
{
Public double TotalArea
{
Get
{
Double acc = 0
{
Forearch (T shape in shapes)
{
Acc + = shape. Area;
}
Return acc;
}
}
Public void add (T shape)
{
Shapes. Add (shape );
}
Private List Shapes = new List ()
}
----------------------- The following are test classes -----------------------------
Public class EntryPoint
{
Static void Main ()
{
Shapes Shapes = new Shapes ();
Shapes. Add (new Circle (2 ));
Shapes. Add (new Rect (3, 5 ));
Console. WriteLine ("Total Area: {0}", shapes. TotalArea );
}
}
The purpose of the test class is to plan the sum of the two Area numbers of the Rect and Circle, but this code compilation will not pass, because during the real-listed Circle and Rect, the generic type does not know the existence of the Area attribute, contact must be implemented. The code can be modified
Public double TotalArea
{
Get
{
Double acc = 0;
{
Forearch (T shape in shapes)
{
IShape theShape = (IShape) shape; // Add a knot
Acc + = shape. Area;
} Return acc;
}
}
To ensure that all types of T have the "Area" type, you can add "Contact" to the class definition and write it as public class Shapes. Where T: The T type such as IShape must implement the IShape interface; otherwise, the compilation fails.