提问人:Mindo 提问时间:2/7/2022 更新时间:2/7/2022 访问量:101
当我尝试将项目添加到房间 [duplicate] 时,我收到 System.NullReferenceException
I Get System.NullReferenceException when I try to add an item into a Room [duplicate]
问:
就像问题中所说,我无法弄清楚为什么我不能在我的房间里添加物品,如果有人对此有见解,我将不胜感激。我不确定是否需要以某种方式将 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;
}
答:
0赞
OneBigQuestion
2/7/2022
#1
我认为你的“Chest”是空的 - 或者可能是你在 Chest 中的列表 - 你必须先实例化对象,然后才能使用它们。
评论