【发布时间】: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