我是 C# 新手,我的编码有问题。我在运行时遇到错误。似乎没有分配对象数组。欢迎任何帮助/提示。我有一个带有修理室的“建筑”类。预计不会改变或增加房间。房间有很多属性。在我的“Home”类中,我想通过对象数组访问所有房间以及特定房间。提前致谢: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); }
1 回答
侃侃尔雅
TA贡献1801条经验 获得超15个赞
您试图在调用Building.Buildings
类的构造函数之前访问静态字段Building
。创建实例后,Building
静态字段将被分配。您可能想使用静态构造函数,如下例所示:
static Building() { ... Buildings = new Building[] { room1, room2 }; }
- 1 回答
- 0 关注
- 77 浏览
添加回答
举报
0/150
提交
取消