在运行时访问对象数组 - System.NullReferenceException

我是 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);



        }


达令说
浏览 78回答 1
1回答

侃侃尔雅

您试图在调用Building.Buildings类的构造函数之前访问静态字段Building。创建实例后,Building静态字段将被分配。您可能想使用静态构造函数,如下例所示:static Building() {     ...     Buildings = new Building[] { room1, room2 }; }
打开App,查看更多内容
随时随地看视频慕课网APP