简体   繁体   中英

C# assigning a class array but value is treated as 0

i'm currently stuck on a project. I have to instantiate a class x amount of times. The value of x can be different every time you run the program. Here is my code for clarification.

 public partial class Form1 : Form
{
    private static int Rooms;              
    private Room[] room = new Room[Rooms]; 

    public Form1()
    {
        InitializeComponent();
        Start();
    }

    private void Start()
    {
        string[] lines = File.ReadAllLines(@"C:Path\Test.txt");
        Rooms = lines.Length;
        for (int i = 0; i < room.Length; i++)
        {
            if (i == 13)
            {
                continue;
            }
            else
            {
                this.room[i] = new Room(i);
            }
            listBox1.Items.Add(this.room[i].RoomNumber.ToString());
        }
    }
}

While debugging, hovering over Rooms at Private static int Rooms; displays the correct value; Hovering over Rooms at private Room[] room = new Room[Rooms]; also displays the correct value, but treats it as if its 0. It doesnt add the room numbers to the listbox. If i use Rooms + 1 , it just adds 1 roomnumber. Though if i replace Rooms with the correct x value, it does work.

Does anyone here know what happens and how to fix this?

Your static variables initialize before the constructor is called (specifically, they are initialized as soon as the class is referenced by code). By default, int variables are initialized to zero, which is why the array has zero elements at first, but shows as the correct value in the debugger. You need to move your array initialization after you assign the Rooms variable:

public partial class Form1 : Form
{
    private static int Rooms;              
    private Room[] room;

    public Form1()
    {
        InitializeComponent();
        Start();
    }

    private void Start()
    {
        string[] lines = File.ReadAllLines(@"C:Path\Test.txt");
        Rooms = lines.Length;
        room = new Room[Rooms]; 
        for (int i = 0; i < room.Length; i++)
        {
            if (i == 13)
            {
                continue;
            }
            else
            {
                this.room[i] = new Room(i);
            }
            listBox1.Items.Add(this.room[i].RoomNumber.ToString());
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM