How to declare an array of objects in C#

后端 未结 7 484
春和景丽
春和景丽 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: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.

提交回复
热议问题