【问题标题】:I get NullReferenceException error but I don't know why? [duplicate]我收到 NullReferenceException 错误,但我不知道为什么? [复制]
【发布时间】:2018-06-02 12:39:46
【问题描述】:

我知道这个错误显示在 object 为 null 的地方。但就我而言,我不确定为什么会显示它。 我尝试在 timer_tick 上以每 30px 的宽度随机创建 10 个 PictureBox 对象,这是我的代码。

PictureBox[] meteor;
int i=0;
Random rnd = new Random();

private void timer1_Tick(object sender, EventArgs e)
{
    if(i<10)
    { 
    int pozicija = rnd.Next(1, 25);
    pozicija *= 30;
    meteor[i] = new PictureBox()
    {
        Name = "pictureBox",
        BackColor = Color.Transparent,
        Size = new Size(80, 60),
        Location = new Point(pozicija, 0),
        Image = imageList2.Images[0],
    };
    this.Controls.Add(meteor[i]);
    }
    i++;
}

错误指向这行代码

this.Controls.Add(meteor[i]);

为什么 Visual Studio 会显示此错误?

【问题讨论】:

  • 从该代码中,您应该更早地在 meteor[i] = new PictureBox() 获得 NullReferenceExeption。
  • @SebastianHofmann 我读到了,但我能找到解决方案,我说我知道它是什么。
  • 在您的情况下,您没有初始化PictureBox[] meteor;,它应该是PictureBox[] meteor = new PictureBox[1000];(或任何其他范围)。
  • @SebastianHofmann 这就是我想要的,谢谢,但不需要负分
  • @DaniloIvanovic 这就是为什么调试器是必不可少的工具。在向任何人寻求帮助之前始终使用它

标签: c# visual-studio nullreferenceexception


【解决方案1】:

在使用之前必须先实例化数组,如下所示:

PictureBox[] meteor = new PictureBox[10];

另外,我假设 imageList2 已被定义,并且您已向其中添加图像。

【讨论】:

    猜你喜欢
    • 2020-08-02
    • 1970-01-01
    • 2017-11-23
    • 2019-02-14
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    相关资源
    最近更新 更多