简体   繁体   中英

Casting a derived member of a base array in c#

I have a base class Shape with two derived classes Circle and Rectangle . Now I have written explicit conversions from Rectangle to Circle and vice versa. They don't make much sense, but that is not my point right now. I create new Rectangle and Circle instances, and want to assign the Rectangle to the Circle with a cast. That works as expected.

But if I have an array of type Shape , which is filled with Rectangles , and want to cast the member of an array, it throws a System.InvalidCastException . As i have written explicit casts, I don't know why this is not possible.

Shape[] arr = new Shape[5];

Circle c1 = new Circle(1, 2, 3);
Circle c2 = new Circle(4, 5, 6);
Rectangle r1 = new Rectangle(7, 8);
Rectangle r2 = new Rectangle(9, 10);
Shape c3 = new Circle(3, 9, 13);

arr[0] = c1;
arr[1] = c2;
arr[2] = r1;
arr[3] = r2;
arr[4] = c3;


Console.WriteLine(r1.GetType());
Console.WriteLine(arr[2].GetType()); // both evalute to Rectangle

Circle r3 = (Circle)r1;             // compiles
Circle r4 = (Circle)arr[2];         // Unhandled Exception

Okay, so as Ondrej pointed out that this is a Cast from Shape to Circle, which is not allowed. However, ingvar pointed out this works:

Circle r5 = (Circle)((Rectangle)arr[2]);    
Rectangle r6 = (Rectangle)((Circle)arr[0]);

and this doesnt

Circle r5 = (Circle)arr[2];   
Rectangle r6 = (Rectangle)arr[0];

Thanks for your help!

Circle r4 = (Circle)arr[2];

The compiler cannot apply the explicit cast, because it cannot statically determine that arr[2] , in fact, stores a Rectangle . For the compiler, it's Shape and hence (Circle)arr[2] is a cast from Shape to Circle .

You cast element of Shape array to Circle directly, that's not possible because in fact your object is Rectangle . Try explicit cast:

Circle r4 = (Circle)((Rectangle)arr[2]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM