C#访问基类数组中派生类的值
本文关键字:派生 访问 基类 数组 | 更新日期: 2023-09-27 18:02:29
这并不完全是我正在处理的问题,但我希望它能成为一个明确的例子:
public abstract class Shape
{
public int Area;
public int Perimeter;
public class Polygon : Shape
{
public int Sides;
public Polygon(int a, int p, int s){
Area = a;
Perimeter = p;
Sides = s;
}
}
public class Circle : Shape
{
public int Radius;
public Circle(int r){
Area = 3.14*r*r;
Perimeter = 6.28*r;
Radius = r;
}
}
}
在主要功能中,我会有这样的东西:
Shape[] ThisArray = new Shape[5];
ThisArray[0] = new Shape.Circle(5);
ThisArray[1] = new Shape.Polygon(25,20,4);
我的问题是,当我处理ThisArray时,我无法访问除Area和Perimeter之外的值例如:
if (ThisArray[0].Area > 10)
//This statement will be executed
if (ThisArray[1].Sides == 4)
//This will not compile
如何从ThisArray访问Sides[1]如果我做了类似
的操作,我可以访问它CCD_ 1,但如果它在形状的阵列中则不是。
如果我没有记错的话,这可以在C++中通过执行类似
的操作来实现Polygon->ThisArray[1].Sides
(我忘了这叫什么(,但我不知道在C#中如何做到这一点
如果我不能做我想做的事情,我该如何绕过这个问题?
感谢您通读我想要简短的内容,任何帮助都将不胜感激。
您应该使用casting:
(ThisArray[1] as Shape.Polygon).Sides
请注意,应该确保基础对象实例实际上是多边形,否则会引发异常。你可以使用类似的东西来做到这一点:
if(ThisArray[1] is Shape.Polygon){
(ThisArray[1] as Shape.Polygon).Sides
}