如何在数组中打印对象?

时间:2011-09-29 23:15:07

标签: c# arrays object

我正在尝试打印多个将作为对象插入到数组中的信息条目,并且我想使用这些对象可用的方法并打印结果。这是我的代码。我在最后两句话中收到错误

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace homework2
{

    class Shapes
    {
        protected string ShapeName;
        protected double ShapeWidth;
        protected double ShapeHeight;

        public Shapes(string ShapeName, double ShapeWidth, double ShapeHeight)

        {
            this.ShapeName = ShapeName;
            this.ShapeWidth = ShapeWidth;
            this.ShapeHeight = ShapeHeight;

        }

    }

    class Rectangle : Shapes 
    {
        public Rectangle(string ShapeName, double ShapeWidth, double ShapeHeight)
            : base(ShapeName, ShapeWidth, ShapeHeight) 
        {
            this.ShapeName = ShapeName;
            this.ShapeWidth = ShapeWidth;
            this.ShapeHeight = ShapeHeight;

        }

        public double GetArea()
        {
            if (ShapeName == "Circle")
            {
                ShapeHeight = 3.14;
                double x = ShapeHeight * (ShapeWidth * ShapeWidth);
                return x;
            }
            else
            {

                double Area = ShapeHeight * ShapeWidth;
                return Area;
            }

        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Rectangle Rec = new Rectangle("Circle",5,2);
            System.Console.WriteLine("This is the Rectangle Area :"+Rec.GetArea());

            System.Console.WriteLine("Please Enter How Many Shapes You want To enter:");
            String x =  Console.ReadLine();
            int y = int.Parse(x);
            for (int i = 0; i <= y; i++ )
            {
                System.Console.WriteLine("Enter Name for Shape No."+i+"Please");
                String ShapeName = Console.ReadLine();
                System.Console.WriteLine("Enter width for Shape No." + i + "Please");
                String ShapeWidth = Console.ReadLine();
                int sw = int.Parse(ShapeWidth);
                System.Console.WriteLine("Enter height for Shape No." + i + "Please");
                String ShapeHeight = Console.ReadLine();
                int sh = int.Parse(ShapeHeight);
                for(int j = 0; j < 4; j++)
                {

                      Rectangle[,] z = new Rectangle[y,4];                    
                Rectangle z[i,j] = new Rectangle(ShapeName, sw, sh);
                }


            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

首先,在派生类Rectangle中,您不需要在形状中重新分配变量,因为仍然会调用基础构造函数。

此外,更有意义的是,不是传入像“Circle”这样的字符串来创建一个圆圈,而是创建一个新的圆圈:实现不同的GetArea()的形状而不是让你的矩形类计算一个圆圈的区域。

您可能犯的错误在于:

Rectangle z[i,j] = new Rectangle(ShapeName, sw, sh);

因为您已经将z [i,j]定义为数组,所以此行应该为

z[i,j] = new Rectangle(ShapeName, sw, sh);

(没有矩形)。

但是,我怀疑你想要在第一个for循环之外定义你的矩形数组。使用当前代码,您将最终得到y个2D数组,每个数组都填充一列。你需要移动它:在第一个for循环之外     Rectangle [,] z = new Rectangle [y,4];