【发布时间】:2019-02-25 00:36:16
【问题描述】:
我有一个数组,其中包含两个值,它们应该代表 x 和 y 图上的一个点,第一个值是该点的 x 值,第二个值是该点的 y 值。
然后我想将一个正方形区域中包含的所有点存储在一个列表中。
我在将数组添加到列表的位置放置了一个断点,它似乎正在将正确的值添加到列表中,即: 100 10 100 9 等等
但是当我运行程序时,它会为列表中的每个数组打印 105 个数组 [0] 和 5 个数组 [1]。
class Program
{
static void Main(string[] args)
{
List<int[]> points = new List<int[]>();
int[] point = new int[2];
string topLeftCornerX = "100";
string topLeftCornerY = "10";
for (int i = int.Parse(topLeftCornerX); i < int.Parse(topLeftCornerX) +6; i++)
{
point[0] = i;
for (int j = int.Parse(topLeftCornerY); j > int.Parse(topLeftCornerY) -6; j--)
{
point[1] = j;
points.Add(point);
}
}
foreach (int[] item in points)
{
Console.WriteLine(item[0]);
Console.WriteLine(item[1]);
}
Console.ReadLine();
}
}
将数组添加到列表的方式或打印值的方式是否存在问题?
【问题讨论】:
-
您可能希望使用
Point结构来存储X和Y坐标。 -
你不断更新
point数组的值,它总是指向同一个内存位置。您应该将其设置为外部循环中的new数组,因此它引用一个新数组(以及内存中的不同位置)。 -
之前有人问过这个问题(就像我选择的duplciate),但你自己可能并不明显。欢迎来到 SO 并感谢您在帖子中提供了非常好的质量 minimal reproducible example。