How to declare an array of objects in C#

后端 未结 7 436
春和景丽
春和景丽 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<T>(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<GameObject>(200);
    
    0 讨论(0)
  • 2020-12-23 16:29

    The reason this is happening is because initializing an array does not initialize each element in that array. You need to first set houses[0] = new GameObject() and then it will work.

    0 讨论(0)
  • 2020-12-23 16:30

    you need to initialize the object elements of the array.

    GameObject[] houses = new GameObject[200];
    
    for (int i=0;`i<house` i<houses.length; i++)
    { houses[i] = new GameObject();}
    

    Of course you initialize elements selectively using different constructors anywhere else before you reference them.

    0 讨论(0)
  • 2020-12-23 16:36

    I guess GameObject is a reference type. Default for reference types is null => you have an array of nulls.

    You need to initialize each member of the array separatedly.

    houses[0] = new GameObject(..);
    

    Only then can you access the object without compilation errors.

    So you can explicitly initalize the array:

    for (int i = 0; i < houses.Length; i++)
    {
        houses[i] = new GameObject();
    }
    

    or you can change GameObject to value type.

    0 讨论(0)
  • 2020-12-23 16:40

    With LINQ, you can transform the array of uninitialized elements into the new collection of created objects with one line of code.

    var houses = new GameObject[200].Select(h => new GameObject()).ToArray();
    

    Actually, you can use any other source for this, even generated sequence of integers:

    var houses = Enumerable.Repeat(0, 200).Select(h => new GameObject()).ToArray();
    

    However, the first case seems to me more readable, although the type of original sequence is not important.

    0 讨论(0)
  • 2020-12-23 16:48

    Everything you have looks fine.

    The only thing I can think of (without seeing the error message, which you should have provided), is that GameObject needs a default (no parameter) constructor.

    0 讨论(0)
提交回复
热议问题