// Make a Rectangle.
Rectangle r = new Rectangle(15, 4);
Console.WriteLine(r.ToString());
r.Draw();
Console.WriteLine();
// Convert r into a Square,
// based on the height of the Rectangle.
Square s = (Square)r;
Console.WriteLine(s.ToString());
s.Draw();
Console.ReadLine();
}
The output can be seen in Figure 12-5.
Figure 12-5.
Converting a Rectangle structure to a Square structure
While it may not be all that helpful to convert a Rectangle into a Square within the same scope,
assume you have a function that has been designed to take Square parameters.
// This method requires a Square type.
static void DrawSquare(Square sq)
{
Console.WriteLine(sq.ToString());
sq.Draw();
}
Using your explicit conversion operation on the Square type, you can now pass in Rectangle
types for processing using an explicit cast:
static void Main(string[] args)
{
...
Do'stlaringiz bilan baham: |