C# 访问基 class 数组中派生 class 的值
C# Accessing values of a derived class in an array of the base class
这不是我正在使用的,但我希望它能提供一个清晰的示例:
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[1] 访问 Sides? 如果我做类似的事情就可以访问它
Shape.Polygon RandomSquare = new Shape.Polygon(25,20,4)
但如果它在形状数组中则不是。
如果我没记错的话,这可以在 C++ 中完成,方法是
Polygon->ThisArray[1].Sides
(我忘了这叫什么)但我不知道在 C# 中如何做到这一点
如果我不能做我想做的事,我该如何规避这个问题?
感谢您阅读我打算简短的内容,感谢您的帮助。
你应该使用转换:
(ThisArray[1] as Shape.Polygon).Sides
请注意,您应该确保底层对象实例实际上是一个多边形,否则会引发异常。你可以通过使用类似的东西来做到这一点:
if(ThisArray[1] is Shape.Polygon){
(ThisArray[1] as Shape.Polygon).Sides
}
这不是我正在使用的,但我希望它能提供一个清晰的示例:
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[1] 访问 Sides? 如果我做类似的事情就可以访问它
Shape.Polygon RandomSquare = new Shape.Polygon(25,20,4)
但如果它在形状数组中则不是。
如果我没记错的话,这可以在 C++ 中完成,方法是
Polygon->ThisArray[1].Sides
(我忘了这叫什么)但我不知道在 C# 中如何做到这一点
如果我不能做我想做的事,我该如何规避这个问题?
感谢您阅读我打算简短的内容,感谢您的帮助。
你应该使用转换:
(ThisArray[1] as Shape.Polygon).Sides
请注意,您应该确保底层对象实例实际上是一个多边形,否则会引发异常。你可以通过使用类似的东西来做到这一点:
if(ThisArray[1] is Shape.Polygon){
(ThisArray[1] as Shape.Polygon).Sides
}