【问题标题】:How to add arrays to a list and print each value of the array for each array in the list in C# [duplicate]如何将数组添加到列表中并在C#中为列表中的每个数组打印数组的每个值[重复]
【发布时间】: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 结构来存储XY 坐标。
  • 你不断更新point数组的值,它总是指向同一个内存位置。您应该将其设置为外部循环中的new 数组,因此它引用一个新数组(以及内存中的不同位置)。
  • 之前有人问过这个问题(就像我选择的duplciate),但你自己可能并不明显。欢迎来到 SO 并感谢您在帖子中提供了非常好的质量 minimal reproducible example

标签: c# arrays list


【解决方案1】:

您不断更新point 数组的值,该数组始终指向相同的内存位置。您应该将其设置为内部循环中的new 数组,以便它引用一个新数组(以及内存中的不同位置),然后在那里分配值。

List<int[]> points = new List<int[]>();            
string topLeftCornerX = "100";
string topLeftCornerY = "10";

for (int i = int.Parse(topLeftCornerX); i < int.Parse(topLeftCornerX) + 6; i++)
{
    for (int j = int.Parse(topLeftCornerY); j > int.Parse(topLeftCornerY) - 6; j--)
    {
        int[] point = new int[2];
        point[0] = i;
        point[1] = j;
        points.Add(point);
    }
}

foreach (int[] item in points)
{
    Console.WriteLine(item[0]);
    Console.WriteLine(item[1]);
}

Console.ReadLine();

话虽如此,使用Point 结构可能更有意义,它具有XY 属性。这比int[] 更具描述性且更易于使用:

List<Point> points = new List<Point>();            
string topLeftCornerX = "100";
string topLeftCornerY = "10";

for (int i = int.Parse(topLeftCornerX); i < int.Parse(topLeftCornerX) + 6; i++)
{
    for (int j = int.Parse(topLeftCornerY); j > int.Parse(topLeftCornerY) - 6; j--)
    {
        points.Add(new Point(i, j);
    }
}

foreach (Point item in points)
{
    Console.WriteLine($"[{item.X}, {item.Y}]");
}

Console.ReadLine();

【讨论】:

  • 有趣的是,只需将原始代码中的 int[] point = new int[2]; 更改为 Point point = new Point(); 并保持其余部分相同也可以修复代码(由于按值复制语义)。这应该会正确混淆 OP :) (我不确定再次回答“添加到列表更改最后一个值”是否是个好主意......但你的帖子看起来很有用且完整,所以不妨投票)
【解决方案2】:

因为在这里您正在修改相同的数组(相同的引用)并将其再次添加到列表中

要让它工作:

在循环的每个循环中,创建数组point = new int[2];的新引用

但是,使用结构或类来表示一个点会更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 2013-05-19
    • 2019-03-19
    • 2017-10-12
    • 1970-01-01
    相关资源
    最近更新 更多