当我尝试将项目添加到房间 [duplicate] 时,我收到 System.NullReferenceException

I Get System.NullReferenceException when I try to add an item into a Room [duplicate]

提问人:Mindo 提问时间:2/7/2022 更新时间:2/7/2022 访问量:101

问:

就像问题中所说,我无法弄清楚为什么我不能在我的房间里添加物品,如果有人对此有见解,我将不胜感激。我不确定是否需要以某种方式将 dicitonary 导入 CreateRooms( ),如果是,如何?

    public void CreateRooms()
    {
        // create the rooms
        Room outside = new Room("outside the main entrance of the university");
        Room hallway = new Room("inside the hallway of the university");
        Room theatre = new Room("in a lecture theatre");
        Room basement = new Room("in the basement");
        Room pub = new Room("in the campus pub");
        Room lab = new Room("in a computing lab");
        Room office = new Room("in the computing admin office");


        // initialise room exits
        outside.AddExit("east", hallway);
        outside.AddExit("south", lab);
        outside.AddExit("west", pub);

        hallway.AddExit("west", outside);
        hallway.AddExit("up", theatre);
        hallway.AddExit("down", basement);


        theatre.AddExit("down", hallway);

        basement.AddExit("up", hallway);

        pub.AddExit("east", outside);

        lab.AddExit("north", outside);
        lab.AddExit("east", office);

        office.AddExit("west", lab);

        Item axe = new Item(5, "a sharp axe");

        outside.Chest.Put("axe", axe); // System.NullReferenceException

        player.currentRoom = outside;  // start game outside
        


    }

这些是将物品放入房间以及我从房间获取/取出物品到库存的方法。

   public bool Put(string itemName, Item item)
    {          
        items.Add(itemName, item);
        Console.WriteLine("There is " + itemName + " in this room. Will you take it?");
        return true;
    }
    public Item Get(string itemName)
    {
        Item item = null;
        if (items.ContainsKey(itemName))
        {
            item = items[itemName];
            items.Remove(itemName);
        }
        return item;
    }
C# 列表 字典 NullReferenceException

评论

0赞 Steve 2/7/2022
副本应该教你关于 NRE 的一切。另外,如果您想要一些提示,至少告诉我们您在哪一行遇到异常。
0赞 Mindo 2/7/2022
@Steve我在出现异常的一行上添加了注释。
0赞 Steve 2/7/2022
因此,您已经创建了外部房间,但是您是否在某处有初始化 Chest 属性的代码?如果不初始化(新)引用类型,则无法使用它

答:

0赞 OneBigQuestion 2/7/2022 #1

我认为你的“Chest”是空的 - 或者可能是你在 Chest 中的列表 - 你必须先实例化对象,然后才能使用它们。