// Assume the length of the new Rectangle with
// (Length x 2)
r.Width = s.Length * 2;
return r;
}
}
With this update, you are now able to convert between types as follows:
static void Main(string[] args)
{
...
// Implicit cast OK!
Square s3;
s3.Length= 7;
Rectangle rect2 = s3;
Console.WriteLine("rect2 = {0}", rect2);
DrawSquare(s3);
// Explicit cast syntax still OK!
Square s4;
s4.Length = 3;
Rectangle rect3 = (Rectangle)s4;
Console.WriteLine("rect3 = {0}", rect3);
Console.ReadLine();
}
Again, be aware that it is permissible to define explicit and implicit conversion routines for the
same type as long as their signatures differ. Thus, you could update the Square as follows:
C H A P T E R 1 2
■
I N D E X E R S, O P E R ATO R S, A N D P O I N T E R S
402
8849CH12.qxd 9/26/07 11:31 AM Page 402
public struct Square
{
...
Do'stlaringiz bilan baham: |