C#/Visual Studio 尝试更改随机数组的内容并出现 'Object reference not set to an instance of an object.' 错误

C#/Visual Studio trying to change the content of random array and getting 'Object reference not set to an instance of an object.' error

我正在尝试制作一个井字游戏,用户输入尺寸,然后创建一个带有按钮的棋盘。当一个按钮被点击时,它被禁用并且里面的文本相应地变为 "X" 或 "O"。用户玩一个非常基本的 "AI",它选择 random.I 处的按钮试图检查板上的空(启用)按钮,但我得到错误:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

代码如下:

public partial class Form1 : Form{
   int num; 
   Button[,] buttonspinak;
   private void button2_Click(object sender, EventArgs e)
        {
            int start = 180, end = 30;

            num = Convert.ToInt32(textBox1.Text);
            buttonspinak = new Button[num, num];

                for (int i = 0; i < num; i++)
                {
                    end += 80;
                    start = 180;

                    for (int j = 0; j < num; j++)
                    {
                        Button b = new Button();
                        b.Size = new Size(60, 60);
                        b.Location = new Point(start, end);
                        this.Controls.Add(b);
                        start += 80;
                        b.BackColor = Color.White;
                        buttonspinak[i, j] = b;
                        b.Click += new EventHandler(Computer2);
                        Computer(sender, e);

                    }
                }
            }
   int countercomputer;
        Random randcompu = new Random();
        private void Computer(object sender, EventArgs e)
        {
            int randomi = 0;
            int randomj = 0;
            Button b = (Button)sender;
            b.Enabled = false;
            randomi = randcompu.Next(0, num);
            randomj = randcompu.Next(0, num);
            **while (buttonspinak[randomi, randomj].Text == "O" || buttonspinak[randomi, randomj].Text == "X")** // this is the line where i get the error
            {
                randomi = randcompu.Next(0, num);
                randomj = randcompu.Next(0, num);
                //buttonspinak[randomi, randomj].Text = "C";
            }
            buttonspinak[randomi, randomj].Text = "O";
            b_Elegxos();

        }
private void Computer2(object sender, EventArgs e)
    {
        countercomputer++;
        Button b = (Button)sender;
        b.Enabled = false;
        if (countercomputer % 2 != 0)
        {
            b.Text = "X";
            b.ForeColor = Color.DarkRed;
        }
        b_Elegxos();

    }
}

您似乎在 button2_Click 处理程序中的嵌套 for 循环的每次迭代中调用 Computer()

这意味着,在仅使用新的 Button 初始化 buttonspinak[0,0] 之后,Computer() 被调用,它在 buttonspinak 中选择一个随机位置并尝试获取该位置元素的 Text。但是,很可能数组中的那个位置还没有初始化,所以你试图在 null 引用上调用 .Text,导致你的异常。

您应该在 button2_Click 中的 for 循环之后调用 Computer(),这样您就可以确保 buttonspinak 中的所有位置都已初始化。