簡體   English   中英

如何初始化二維對象

[英]How to initialize 2D object

我試圖弄清楚如何開始一個對象的二維數組。 我有點類,我想創建從二維點數組構建的 Rectangle 類。 我想像這樣初始化public Point[,] StartPoint somting = new [,]Point(); 正確的方法是什么?

{
class Point
{
    public int X { get; set; }
    public int Y { get; set; }

    public Point()
    {
        X = 0;
        Y = 0;
    }
    public Point(int x , int y)
    {
        X = x;
        Y = y;
    }
}
}

矩形類:

{
class SRectangle
{
    public Point[,] StartPoint;
    public int Rows ;
    public int Cols ;



    public SRectangle(Point start , int row, int col)
    {
        Rows = row;
        Cols = col;
        for (int i = 0; i <= Rows; i++)
        {
            for (int j = 0; j <= Cols; j++)
            {
                StartPoint[i, j] = new Point(Rows + i, Cols + j);
            }
        }
    }
}

}

您不需要多維數組來存儲點,它們本身存儲 x 和 y。 你只需要一個矩形的簡單數組 f 點,但我看到你的擔心,你似乎想要的是:

但因為它是類我不能寫這樣的'public Point[,] StartPoint = new Point,;

您希望使用索引訪問點,就像存儲 X 和 Y 組合一樣。 但你不是,你正在存儲一個對象數組,其中包含有關 X 和 Y 的信息,但是有一種方法可以通過 (x,y)index

  1. 堅持使用 2d 數組,其中Points[x,y]將有一個具有相同 X 和 Y 的對象,即您可能已經存儲了int[,]並且這無關緊要。

  2. 將數組視為 2d 但實際上具有 1d 數組。

//my rectangle class
class Rectangle
{
    public Point[,] Points;
    public int Rows ;
    public int Cols ;



    public Rectangle(Point start, int row, int col)
    {
        Rows = row;
        Cols = col;
        Points = new Point[Rows, Cols];
        for (int i = 0; i <= Rows; i++)
        {
            for (int j = 0; j <= Cols; j++)
            {
                Points[i, j] = new Point(Rows + i, Cols + j);
            }
        }
        //now use it like Points[x, y]
    }
}
//my rectangle class
class Rectangle
{
    public Point[] Points;
    public int Rows;
    public int Cols;

    public Rectangle(Point start, int row, int col)
    {
        Rows = row;
        Cols = col;
        Points = new Point[Rows * Cols];
        for (int i = 0; i <= Rows; i++)
        {
            for (int j = 0; j <= Cols; j++)
            {
                Points[(i * Cols) + j] = new Point(Rows + i, Cols + j);
            }
        }
    }
        
    //return the point if it exists else null
    public Point? GetPoint(int x, int y)
    {
       int index = (i * Cols) + j;
       if (index < Points.Length)
           return Points[index];
       return null;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM