【发布时间】:2019-08-22 15:04:24
【问题描述】:
我有一个基类Shape 和两个派生类Circle 和Rectangle。现在我已经编写了从Rectangle 到Circle 的显式转换,反之亦然。它们没有多大意义,但这不是我现在的观点。我创建了新的 Rectangle 和 Circle 实例,并希望将 Rectangle 分配给带有演员表的 Circle。这按预期工作。
但如果我有一个类型为Shape 的数组,其中填充了Rectangles,并且想要转换数组的成员,它会抛出一个System.InvalidCastException。因为我已经写了明确的演员表,我不知道为什么这是不可能的。
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
好的,正如 Ondrej 指出的,这是从形状到圆形的转换,这是不允许的。然而,ingvar 指出这是可行的:
Circle r5 = (Circle)((Rectangle)arr[2]);
Rectangle r6 = (Rectangle)((Circle)arr[0]);
这不是
Circle r5 = (Circle)arr[2];
Rectangle r6 = (Rectangle)arr[0];
感谢您的帮助!
【问题讨论】:
标签: c# arrays class casting derived