Instantiate an array of objects, in simpliest way?

后端 未结 3 2214
傲寒
傲寒 2020-12-18 11:28

Given a class:

class clsPerson { public int x, y; }

Is there some way to create an array of these classes with each element initialized to

3条回答
  •  [愿得一人]
    2020-12-18 12:15

    The constructor must be run for every item in the array in this scenario. Whether or not you use a loop, collection initializers or a helper method every element in the array must be visited.

    If you're just looking for a handy syntax though you could use the following

    public static T[] CreateArray(int count) where T : new() {
      var array = new T[count];
      for (var i = 0; i < count; i++) {
        array[i] = new T();
      }
      return array;
    }
    
    clsPerson[] objArary = CreateArray(1000);
    

提交回复
热议问题