我有一个持有图片盒的课程。我创建了一个类的对象数组,但是当我尝试创建一个新的图片框时,我收到一个错误说明,对象引用未设置为对象的实例。
以下是我创建图片框的方法
GreyHound[] dog;
public Form1()
{
InitializeComponent();
dog[1].MyPictureBox = new PictureBox();
dog[1].MyPictureBox = pictureBox1;
dog[2].MyPictureBox = new PictureBox();
dog[2].MyPictureBox = pictureBox2;
dog[3].MyPictureBox = new PictureBox();
dog[3].MyPictureBox = pictureBox3;
dog[4].MyPictureBox = new PictureBox();
dog[4].MyPictureBox = pictureBox4;
编辑代码:
GreyHound []狗;
public Form1()
{
InitializeComponent();
dog = new GreyHound[4];
dog[0].MyPictureBox = new PictureBox();
dog[0].MyPictureBox = pictureBox1;
dog[1].MyPictureBox = new PictureBox();
dog[1].MyPictureBox = pictureBox2;
dog[2].MyPictureBox = new PictureBox();
dog[2].MyPictureBox = pictureBox3;
dog[3].MyPictureBox = new PictureBox();
dog[3].MyPictureBox = pictureBox4;
}
答案 0 :(得分:3)
您拥有的代码有几个严重的问题:
NullReferenceException
的原因有两个:
GreyHound
数组,但您从未初始化它。这意味着,dog
为null
并尝试访问dog[1]
会导致NullReferenceException。GreyHound
是一个引用类型,这意味着您必须为数组中的每个项创建一个实例。使用当前代码,数组中的所有项都为null
,当尝试访问数组中任何项目的属性NullReferenceException
时会导致MyPictureBox
,因为dog[1]
会是null
。PictureBox
的新实例分配给属性MyPictureBox
,但是使用pictureBoxX
覆盖下一行中的该值。修复你的代码:
GreyHound[] dog = new GreyHound[4]; // solves problem 1.1
dog[0] = new GreyHound(); // solves problem 1.2
dog[0].MyPictureBox = pictureBox1;
dog[1] = new GreyHound(); // solves problem 1.2
dog[1].MyPictureBox = pictureBox2;
dog[2] = new GreyHound(); // solves problem 1.2
dog[2].MyPictureBox = pictureBox3;
dog[3] = new GreyHound(); // solves problem 1.2
dog[3].MyPictureBox = pictureBox4;
答案 1 :(得分:2)
您不会在任何地方初始化数组:
dog = new GreyHound[4];
数组索引也从0开始,所以:
dog[0].MyPictureBox = new PictureBox();
dog[0].MyPictureBox = pictureBox1;
dog[1].MyPictureBox = new PictureBox();
dog[1].MyPictureBox = pictureBox2;
dog[2].MyPictureBox = new PictureBox();
dog[2].MyPictureBox = pictureBox3;
dog[3].MyPictureBox = new PictureBox();
dog[3].MyPictureBox = pictureBox4;