I'm trying to figure out how to start a two dimensional array of an object. I have point class and I want to create Rectangle class that build from 2D arrays of points. I want to initialize the public Point[,] StartPoint
somting like this = new [,]Point();
What the right way to do it?
{
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;
}
}
}
Rectangele class :
{
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);
}
}
}
}
}
You don't need a multidimensional array to keep a store of points, they themselves store x and y. You only need a simple array f points for a rectangle, But I see your concern, what you seem to want is:
but because it is class I can't write something like this 'public Point[,] StartPoint = new Point,;
You want to access points using an index as if you were storing X and Y combinations. But You aren't, you're storing an array of objects which have information about X and Y's however there is a way to get the point by (x,y)index
Insist on using a 2d array, in which Points[x,y]
will have an object with the same X and Y ie you might as well have stored int[,]
and it wouldn't have mattered.
Treat the array as a 2d but really having a 1d array.
//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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.