图片框始终抛出未设置为对象错误实例的对象引用

时间:2013-05-28 06:50:55

标签: c#

我有一个持有图片盒的课程。我创建了一个类的对象数组,但是当我尝试创建一个新的图片框时,我收到一个错误说明,对象引用未设置为对象的实例。

以下是我创建图片框的方法

 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;



    }

2 个答案:

答案 0 :(得分:3)

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

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

    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;