繁体   English   中英

C#访问基类数组中的派生类的值

[英]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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM