当我创建一个数组时,它显示为null

时间:2018-04-28 12:29:51

标签: c# arrays

我目前正试图将monolopy作为一个小项目。 我正在尝试创建一个Tiles数组,但是当我运行代码时,我得到一个nullreferenceException,因为Tile [] Tiles显示为null。任何建议都会很棒。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Monolopy
{
class Board
{
     public Tile[] Tiles { get; }
     GoTile tile1;
     BuildingTile tile2;
     JailTile tile3;
     BuildingTile tile4;
     BuildingTile tile5;
     BuildingTile tile6;
     GoToJailTile tile7;
     BuildingTile tile8;
     BuildingTile tile9;
     ChanceTile tile10;
     BuildingTile tile11;
     BuildingTile tile12;



    public Board()
    {
        Tile[] Tiles = {
            tile1 = new GoTile(),
            tile2 = new BuildingTile(2, "Old Kent Road", 20, 200),
            tile3 = new JailTile(),
            tile4 = new BuildingTile(4, "WhiteHall", 40, 400),
            tile5 = new BuildingTile(5, "Euston Road", 50, 500),
            tile6 = new BuildingTile(6, "bow Street", 60, 600),
            tile7 = new GoToJailTile(),
            tile8 = new BuildingTile(8, "Strand", 70, 700),
            tile9 = new BuildingTile(9, "Fleet Street", 80, 800),
            tile10 = new ChanceTile(),
            tile11 = new BuildingTile(11, "Park Lane", 90, 900),
            tile12 = new BuildingTile(12, "Mayfair", 100, 1000)
        };
    }
}

}

2 个答案:

答案 0 :(得分:1)

您在构造函数中重新声明了Tiles,因此永远不会设置实例属性。只需在构造函数中省略Tile []类型即可。

此外,向属性添加(私有)setter。

答案 1 :(得分:0)

构造函数中的Tile数组在构造函数中是 local 变量,因此使用类 Board 的属性 Tiles 的任何代码都将为null 。 Tiles 成员实际上从未初始化。

尝试将本地变量的值分配给您的属性。