0

如何将我的四个形状放入我创建的对象数组中?使用

shapeArray[0] = (1,2,3,4)

这是我能想到的,这显然是不正确的......

struct Shapes
{
    private int width;
    private int height;
    private int xAxis;
    private int yAxis;
}

Shapes[] shapeArray = new Shapes[4];
4

2 回答 2

1

你应该为你的 Shape 添加一个新的构造函数:

struct Shape
{
    public Shape(int width, int height, int xAxis, int yAxis)
    {
        this.width = width;
        this.height = height;
        this.xAxis = xAxis;
        this.yAxis = yAxis;
    }

    private int width;
    private int height;
    private int xAxis;
    private int yAxis;

    public int Width { get { return width; } }
    public int Height { get { return height; } }
    public int XAxis { get { return xAxis; } }
    public int YAxis { get { return yAxis; } }
}

然后你可以用它来创建它:

Shape[] shapes = new Shape[]{
    new Shape(1, 2, 3, 4),
    new Shape(2, 4, 6, 8),
    new Shape(1, 2, 3, 4),
    new Shape(4, 3, 2, 1)
};
于 2013-01-03T19:59:14.463 回答
0

由于您没有为您创建构造函数Shapes,因此您必须明确设置属性

shapeArray[0] = new Shapes;
shapeArray[0].width = 1; 
shapeArray[0].height = 2;
shapeArray[0].xAxis = 3;
shapeArray[0].yAxis = 4;

然而,正确的方法(并避免使用可变结构)是将公共字段私有化并将构造函数添加到您的结构中:

public Shapes(int width, int height, int xAxis, int yAxis)
{ 
    this.width = width; 
    this.height = height;
    this.xAxis = xAxis;
    this.yAxis = yAxis;
}

然后你就用

shapeArray[0] = new Shapes(1, 2, 3, 4);
于 2013-01-03T19:57:59.290 回答