How to declare an array of objects in C#

后端 未结 7 483
春和景丽
春和景丽 2020-12-23 16:12

I have a very beginning C# question. Suppose I have a class called GameObject, and I want to create an array of GameObject entities. I could think

7条回答
  •  醉酒成梦
    2020-12-23 16:28

    The issue here is that you've initialized your array, but not its elements; they are all null. So if you try to reference houses[0], it will be null.

    Here's a great little helper method you could write for yourself:

    T[] InitializeArray(int length) where T : new()
    {
        T[] array = new T[length];
        for (int i = 0; i < length; ++i)
        {
            array[i] = new T();
        }
    
        return array;
    }
    

    Then you could initialize your houses array as:

    GameObject[] houses = InitializeArray(200);
    

提交回复
热议问题