【问题标题】:C# Accessing values of a derived class in an array of the base classC#访问基类数组中派生类的值
【发布时间】: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


【解决方案1】:

你应该使用强制转换:

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

请注意,您应该确保底层对象实例实际上是一个多边形,否则这将引发异常。你可以使用类似的东西来做到这一点:

if(ThisArray[1] is Shape.Polygon){
    (ThisArray[1] as Shape.Polygon).Sides
}

【讨论】:

  • 谢谢,这就是我要找的东西,我只是不知道我要找什么或 C# 中使用的格式。虽然你不得不说 Shape.Polygon 而不仅仅是 Polygon。
  • 你是对的,因为它是一个内部类。已编辑。 PS:如果您认为这是正确的答案,请记住接受此答案;)
猜你喜欢
  • 1970-01-01
  • 2021-06-21
  • 2011-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多