将值分配给For循环内对象数组的属性

问题描述 投票:0回答:1

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

方法:我使用的是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
1个回答
1
投票

您的问题会发生,因为即使将数组定义为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());  
© www.soinside.com 2019 - 2024. All rights reserved.