简体   繁体   English

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

[英]C# Accessing values of a derived class in an array of the base class

This is not exactly what I am working with but I hope it makes a clear example: 这不是我正在使用的工具,但我希望它提供一个明确的例子:

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;
         }
     }
}

In the main function I would have something like this: 在主函数中,我将具有以下内容:

Shape[] ThisArray = new Shape[5];
ThisArray[0] = new Shape.Circle(5);
ThisArray[1] = new Shape.Polygon(25,20,4);

My problem is that when I deal with ThisArray, I can't access values other than Area and Perimeter. 我的问题是,当我处理ThisArray时,我无法访问Area和Perimeter以外的其他值。 For example: 例如:

if (ThisArray[0].Area > 10)
   //This statement will be executed

if (ThisArray[1].Sides == 4)
   //This will not compile

How can I access Sides from ThisArray[1]? 如何从ThisArray [1]访问Sides? I could access it if I did something like 如果我做了类似的事情,我可以访问它
Shape.Polygon RandomSquare = new Shape.Polygon(25,20,4) but not if it is in an array of shapes. Shape.Polygon RandomSquare = new Shape.Polygon(25,20,4)但如果它是形状数组,则不是。

If I recall correctly this could be accomplished in C++ by doing something like 如果我没记错的话,这可以通过C ++通过执行类似的操作来完成
Polygon->ThisArray[1].Sides (I forget what this is called) but I do not know how do this in C# Polygon->ThisArray[1].Sides (我忘了这叫什么),但我不知道如何在C#中做到这一点

If I can't do what I am trying to do, how can I circumvent this problem? 如果我做不到自己想做的事,该如何解决这个问题?

Thank you for reading through what I intended to be short, any help is appreciated. 感谢您阅读我打算简短介绍的内容,感谢您的帮助。

You should use casting: 您应该使用强制转换:

(ThisArray[1] as Shape.Polygon).Sides

Note that you should make sure the underlying object instance actually IS a Polygon, otherwise this will raise an exception. 请注意,您应确保基础对象实例实际上是多边形,否则将引发异常。 You can do this by using something like: 您可以使用以下方法来做到这一点:

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