遇到了奇怪的循环行为

时间:2013-12-01 18:37:48

标签: c# arrays

我觉得有点愚蠢,但我无法找到解决方案,所以我在这里问。我的代码的目的是用0到255之间的随机数填充2D数组4x4并将它们渲染到面板。问题是,我有两个函数:RenderArray()和WriteToTextbox()。只有当其中一个从数组中读取为数组[y,x]而不是数组[x,y]时,它们才从数组中返回相同的值。我觉得这种行为很奇怪,我不能简单地想到原因。这是代码:

    private bool newRequest;
    private bool hasGenerated;
    private int[,] array = new int[4, 4];
    private static Random random = new Random();

    private void btnRandom_Click(object sender, EventArgs e)
    {
        if (!HasGenerated)
        {
            HasGenerated = true;
        }

        NewRequest = true;
        pnlRandom.Refresh();
    }

    public bool NewRequest
    {
        get { return newRequest; }
        set { newRequest = value; }
    }

    public bool HasGenerated
    {
        get { return hasGenerated; }
        set { hasGenerated = value; }
    }

    public static Random GetRandom
    {
        get { return random; }
    }

    private void pnlRandom_Paint(object sender, PaintEventArgs e)
    {
        if (!HasGenerated)
        {
            return;
        }

        if (NewRequest)
        {
            for (int x = 0; x < 4; x++)
            {
                for (int y = 0; y < 4; y++)
                {
                    array[x, y] = GetRandom.Next(0, 256);
                }
            }

            NewRequest = false;
        }

        RenderArray(e);
        WriteToTextbox();
    }

    private void RenderArray(PaintEventArgs e)
    {
        Graphics g = e.Graphics;

        for (int x = 0; x < 4; x++)
        {
            for (int y = 0; y < 4; y++)
            {
                //int color = array[y, x]; If I write it like that
                //they will return same values.
                int color = array[x, y];
                SolidBrush brush = new SolidBrush(Color.FromArgb(color, color, color));
                Rectangle rect = new Rectangle(x * 64, y * 64, 64, 64);

                g.FillRectangle(brush, rect);
            }
        }
    }

    private void WriteToTextbox()
    {
        txtRandom.Clear();

        for (int x = 0; x < 4; x++)
        {
            for (int y = 0; y < 4; y++)
            {
                int length = array[x, y].ToString().Length;
                txtRandom.Text += array[x, y].ToString().PadLeft(3 * 4 - length + 3 * 4 % 3);
            }

            txtRandom.Text += "\r\n";
        }
    }

1 个答案:

答案 0 :(得分:1)

你以错误的顺序迭代循环。

绘制数组时,首先遍历xy并不重要;无论哪种方式,每个单元格都将绘制在您传递给FillRectangle()的坐标处。

将数组打印到字符串时,按照迭代它们的顺序编写字符 通过循环x,然后y,您循环遍历数组中的每个x),然后循环将单元格垂直向下抛出该列(y)。
因此,您正在打印转置的数组。