首页 > 解决方案 > 为For循环内对象数组的属性赋值

问题描述

背景:我正在为我的学校作业编写一个益智游戏。我有一个保存在文本文件中的益智游戏。现在我通过读取保存的文本文件将其加载到表单中。在文本文件中,前两行是图块(2d 图片框)的总行数和列数,接下来的行是每个图片框的行号、列号和图像索引。

方法:我正在使用 Tile(从 PictureBox 类继承的自定义控件类)引用的二维数组,并使用嵌套循环来读取每个 tile 的(PictureBoxes')信息,即。行号、列号和图像索引。tile 类具有名为 Row、Column 和 TileType 的属性。我正在尝试为嵌套循环内的属性赋值。

//Tile Class
public class Tile : PictureBox
{
   private int row;
   private int column;
   private int tileType;
   public int Row{get; set;}
   public int Column { get; set; }
   public int TileType { get; set; }
}
public Tile[,] LoadPictureBoxes(string filename)
{
  Tile[,] tile;
  //Read the file 
  if (System.IO.File.Exists(filename) == true)
  {
    StreamReader load = new StreamReader(filename);
    int nRow = int.Parse(load.ReadLine());
    int nCol = int.Parse(load.ReadLine());
    //declare two dimensional array of Tile Reference
    tile = new Tile[nRow, nCol];
    //using nested loop to read each tile's information
    for(int i=0; i < nRow; i++)
    {
      for(int j=0; j < nCol; j++)
      {
        tile[i, j].Row = int.Parse(load.ReadLine());   //gets an exception here
        tile[i, j].Column = int.Parse(load.ReadLine());  //gets an exception here
        tile[i, j].TileType = int.Parse(load.ReadLine());  //gets an exception here
      }
    }
    load.Close();
    return tile;
  }

  return new Tile[0, 0];
}

private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
  DialogResult r = dlgLoad.ShowDialog();

  switch (r)
  {
  case DialogResult.Cancel:
    break;
  case DialogResult.OK:
    string fileName = dlgLoad.FileName;
    Tile[,] tile = LoadPictureBoxes(fileName);
    int leftPos = 100;
    int topPos = 0;
    int height = 100;
    int width = 100;
    int rowCount = 0;
    int columnCount = 0;
    //loop after each row of picturebox is generated
    for (int rowNumber = 0; rowNumber < tile.GetLength(0); ++rowNumber)
    {
      ++rowCount;
      for (int colNumber = 0; colNumber < tile.GetLength(1); ++colNumber)
      {
        ++columnCount;
        Tile pic = new Tile();
        pic.Left = leftPos;
        pic.Top = topPos;
        pic.Height = height;
        pic.Width = width;
        pic.BorderStyle = BorderStyle.Fixed3D;
        pic.SizeMode = PictureBoxSizeMode.StretchImage;
        tile[rowCount, columnCount] = pic;
        pnlLoadGame.Controls.Add(pic);
        leftPos += width;
      }
      topPos += height;
    }
    pnlLoadGame.Size = new Size(100 * rowCount, 100 * columnCount);
    pnlGameScore.Left = 100 + 100 * columnCount;
    break;
  }
}

问题:我在运行时遇到异常:System.NullReferenceException:“对象引用未设置为对象的实例。” 是否有另一种方法可以为自定义 PictureBox 的属性赋值?

标签: c#streamreader

解决方案


出现问题是因为即使您将数组定义为tile = new Tile[nRow, nCol];,您仍然需要在使用它们之前初始化其元素。像这样:

tile[i, j] = new Tile();

之后,可以安全地执行以下三行:

tile[i, j].Row = int.Parse(load.ReadLine());
tile[i, j].Column = int.Parse(load.ReadLine());  
tile[i, j].TileType = int.Parse(load.ReadLine());  

推荐阅读