[英]Casting a derived member of a base array in c#
我有一個帶有兩個派生類Circle
和Rectangle
的基類Shape
。 現在,我編寫了從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];
謝謝你的幫助!
Circle r4 = (Circle)arr[2];
編譯器無法應用顯式強制轉換,因為它不能靜態確定arr[2]
實際上存儲了Rectangle
。 對於編譯器,它是Shape
,因此(Circle)arr[2]
是從Shape
到Circle
。
您將Shape
數組的元素直接轉換為Circle
,這是不可能的,因為實際上您的對象是Rectangle
。 嘗試顯式強制轉換:
Circle r4 = (Circle)((Rectangle)arr[2]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.