我有一個Shape包含兩個派生類的基類Circle和Rectangle. 現(xiàn)在我已經(jīng)編寫了從Rectangle到 的顯式轉(zhuǎn)換,Circle反之亦然。它們沒有多大意義,但這不是我現(xiàn)在的意思。我創(chuàng)建了新的Rectangle和Circle實例,并希望通過強制轉(zhuǎn)換將其分配Rectangle給Circle。這按預(yù)期工作。但是,如果我有一個類型為 的數(shù)組Shape,其中填充了Rectangles,并且想要轉(zhuǎn)換數(shù)組的成員,它會拋出一個System.InvalidCastException. 因為我已經(jīng)寫了明確的演員表,所以我不知道為什么這是不可能的。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 RectangleCircle r3 = (Circle)r1; // compilesCircle r4 = (Circle)arr[2]; // Unhandled Exception好的,正如 Ondrej 指出的那樣,這是從形狀到圓形的轉(zhuǎn)換,這是不允許的。然而,ingvar 指出這是可行的:Circle r5 = (Circle)((Rectangle)arr[2]); Rectangle r6 = (Rectangle)((Circle)arr[0]);這不是Circle r5 = (Circle)arr[2]; Rectangle r6 = (Rectangle)arr[0];謝謝你的幫助!
2 回答

HUWWW
TA貢獻1874條經(jīng)驗 獲得超12個贊
Circle r4 = (Circle)arr[2];
編譯器無法應(yīng)用顯式強制轉(zhuǎn)換,因為它無法靜態(tài)確定arr[2]
實際上存儲了一個Rectangle
. 對于編譯器,它是Shape
并且因此(Circle)arr[2]
是從Shape
到的轉(zhuǎn)換Circle
。

青春有我
TA貢獻1784條經(jīng)驗 獲得超8個贊
您將Shape
數(shù)組的元素Circle
直接轉(zhuǎn)換為,這是不可能的,因為實際上您的對象是Rectangle
. 嘗試顯式轉(zhuǎn)換:
Circle r4 = (Circle)((Rectangle)arr[2]);
- 2 回答
- 0 關(guān)注
- 147 瀏覽
添加回答
舉報
0/150
提交
取消