0

我有一堂课,里面有一个图片框。我已经创建了一个类的对象数组,但是当我尝试创建一个新的图片框时,我收到一条错误消息,指出对象引用未设置为对象的实例。

这是我创建图片框的方式

 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;

编辑代码:

灰狗[] 狗;

    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;



    }
4

2 回答 2

3

您的代码有几个严重的问题:

  1. 你的原因NullReferenceException有两个:
    1. 你声明了一个数组GreyHound,但你从不初始化它。这意味着,尝试访问dog会导致 NullReferenceException。nulldog[1]
    2. 如果您要解决这个问题,您仍然会遇到另一个问题:
      假设这GreyHound是一个引用类型,这意味着您必须为数组中的每个项目创建一个实例。使用您当前的代码,数组中的所有项目都是在尝试访问数组中任何项目的属性时null导致.NullReferenceExceptionMyPictureBoxdog[1]null
  2. 对于数组中的每个项目,首先将 a 的新实例分配给PictureBox属性MyPictureBox,但在下一行用 覆盖该值pictureBoxX
  3. 正如我们在 C# 中一样,数组的索引为零,因此第一项的索引为 0 而不是 1。

像这样修复您的代码:

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;
于 2013-05-28T06:55:00.280 回答
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;
于 2013-05-28T06:54:11.173 回答