我一直在尝试创建一个结构,然后使用该结构来创建一个2D数组,但我不断收到关于该类型的错误(无法将类型' int'转换为Point)。这是我的代码:
public struct Point
{
public int x, y;
};
static void Main(string[] args)
{
Point[,] points = { { 0, 0 }, { 1, 0 }, { 2, 1 }, { 1, 2 }, { 0, 2 } };
}
我有什么想法可以解决这个问题?我对编程比较陌生,需要一些指导:)
答案 0 :(得分:1)
您似乎正在尝试创建Point
的良好旧 1D 数组:
Point[] points = new Point[] {
new Point() {x = 0, y = 0 },
new Point() {x = 1, y = 0 },
new Point() {x = 2, y = 1 },
new Point() {x = 1, y = 2 },
new Point() {x = 0, y = 2 },
};
如果您不想成为罗嗦,可以稍微修改Point
:
public struct Point {
public Point(int x, int y) {
X = x;
Y = y;
}
//DONE: Exposing fields is a bad practice; converted to property
//DONE: struct are often immutable (private set)
public int X {get; private set;}
public int Y {get; private set;}
}
然后你可以做
Point[] points = new Point[] {
new Point(0, 0),
new Point(1, 0),
new Point(2, 1),
new Point(1, 2),
new Point(0, 2),
};