访问对象数组-运行时 System.NullReferenceException [重复]
Posted
技术标签:
【中文标题】访问对象数组-运行时 System.NullReferenceException [重复]【英文标题】:Access an Object Array - System.NullReferenceException during runtime [duplicate] 【发布时间】:2019-12-28 04:54:14 【问题描述】:我是 C# 新手,我的编码有问题。我在运行时出错。似乎没有分配对象数组。欢迎任何帮助/提示。我有一个带固定房间的“建筑”类。预计不会有任何变化或额外的房间。 房间有很多属性。在我的“家庭”课程中,我想通过对象数组和特定房间访问所有房间。 提前致谢:
Class Home
private void StartProgramm()
//get all Objects of class "Building"
Building[] building = Building.Buildings;
//System.NullReferenceException during runtime
set_label_header(building[0].Name);
//Access to room1
Building room1 = Building.room1;
set_label_header(room1.Name);
//Get room2
Building room2 = Building.GetBuilding("room2");
set_label_header(room2?.Name);
class Building
public string Name get; set;
public ArrayList tool_groupList = new ArrayList();
public ArrayList pos_List = new ArrayList();
public ArrayList inv_list = new ArrayList();
public static Building room1;
public static Building room2;
public static Building[] Buildings;
public Building()
//create room 1 and add some attributes
room1 = new Building Name = "room1" ;
room1.tool_groupList.Add(1);
room1.tool_groupList.Add(2);
room1.pos_List.Add(14);
room1.pos_List.Add(15);
room1.pos_List.Add(16);
room1.pos_List.Add(17);
Iventory[] inventories = Inventory.get_inventories();
room1.areaList.AddRange(inventories);
//create room 2 and add some attributes
room2 = new Building Name = "room2" ;
room2.tool_groupList.Add(2);
room2.pos_List.Add(1);
room2.pos_List.Add(2);
room2.pos_List.Add(9);
room2.pos_List.Add(10);
room2.pos_List.Add(13);
room2.pos_List.Add(14);
room2.pos_List.Add(15);
room2.pos_List.Add(16);
Iventory[] inventories = Inventory.get_inventories();
room2.areaList.AddRange(inventories);
//Array with all rooms
Buildings = new Building[] room1, room2 ;
//get single room by name
public static Building GetBuilding(string name)
foreach (Building Building in Buildings)
if( Building.Name != null && Building.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
return Building;
return null;
【问题讨论】:
您能帮我们找出错误所在的确切行吗? set_label_header(building[0].Name); 好吧,我最好的猜测是当您尝试访问building[0]
时building
为空。既然building
不存在,那么它就不能给你building[0]
。你有没有在调试模式下跳过代码?
【参考方案1】:
您正试图在调用 Building
类的构造函数之前访问静态字段 Building.Buildings
。创建Building
的实例后,将分配静态字段。您可能希望使用如下示例中的静态构造函数:
static Building()
...
Buildings = new Building[] room1, room2 ;
【讨论】:
谢谢,这就是解决方案以上是关于访问对象数组-运行时 System.NullReferenceException [重复]的主要内容,如果未能解决你的问题,请参考以下文章