【发布时间】:2015-07-14 08:10:17
【问题描述】:
这不是我正在使用的,但我希望它是一个明确的例子:
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 时,我无法访问除面积和周长之外的值。 例如:
if (ThisArray[0].Area > 10)
//This statement will be executed
if (ThisArray[1].Sides == 4)
//This will not compile
如何从 ThisArray[1] 访问 Sides? 如果我执行类似Shape.Polygon RandomSquare = new Shape.Polygon(25,20,4) 之类的操作,则可以访问它,但如果它位于形状数组中,则不能访问它。
如果我没记错的话,这可以在 C++ 中通过执行类似Polygon->ThisArray[1].Sides(我忘记这叫什么)来完成,但我不知道如何在 C# 中做到这一点
如果我不能做我想做的事,我该如何规避这个问题?
感谢您阅读我打算简短的内容,感谢您提供任何帮助。
【问题讨论】:
-
您实际上应该做什么重新考虑您的设计,在其中您保留一系列形状但期望特定的多边形行为。将派生类放在基类中也不是惯用的 C#。
标签: c# arrays class base derived