[英]Casting a derived member of a base array in c#
I have a base class Shape
with two derived classes Circle
and Rectangle
. 我有一个带有两个派生类Circle
和Rectangle
的基类Shape
。 Now I have written explicit conversions from Rectangle
to Circle
and vice versa. 现在,我编写了从Rectangle
到Circle
显式转换,反之亦然。 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. 我创建了新的Rectangle
和Circle
实例,并希望通过强制转换将Rectangle
分配给Circle
。 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
. 但是,如果我有类型的数组Shape
,这是充满Rectangles
,想投一个数组的成员,它抛出一个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. 好的,正如Ondrej指出的那样,这是从形状到圆的强制转换,这是不允许的。 However, ingvar pointed out this works: 但是,ingvar指出这可行:
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
. 编译器无法应用显式强制转换,因为它不能静态确定arr[2]
实际上存储了Rectangle
。 For the compiler, it's Shape
and hence (Circle)arr[2]
is a cast from Shape
to Circle
. 对于编译器,它是Shape
,因此(Circle)arr[2]
是从Shape
到Circle
。
You cast element of Shape
array to Circle
directly, that's not possible because in fact your object is Rectangle
. 您将Shape
数组的元素直接转换为Circle
,这是不可能的,因为实际上您的对象是Rectangle
。 Try explicit cast: 尝试显式强制转换:
Circle r4 = (Circle)((Rectangle)arr[2]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.