Instantiate an array of objects, in simpliest way?

ぐ巨炮叔叔 提交于 2019-12-10 10:45:40

问题


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 a (default) constructed instance, without doing it manually in a for loop like:

clsPerson[] objArr = new clsPerson[1000];

for (int i = 0; i < 1000; ++i)
    objArr[i] = new clsPerson();

Can I shorten the declaration and instantiation of an array of N objects?


回答1:


You must invoke the constructor for each item. There is no way to allocate an array and invoke your class constructors on the items without constructing each item.

You could shorten it (a tiny bit) from a loop using:

clsPerson[] objArr = Enumerable.Range(0, 1000).Select(i => new clsPerson()).ToArray();

Personally, I'd still allocate the array and loop through it (and/or move it into a helper routine), though, as it's very clear and still fairly simple:

clsPerson[] objArr = new clsPerson[1000];
for (int i=0;i<1000;++i) 
   clsPerson[i] = new clsPerson(); 



回答2:


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<T>(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<clsPerson>(1000);



回答3:


If it would make sense to do so, you could change class clsPerson to struct Person. structs always have a default value.



来源:https://stackoverflow.com/questions/9333232/instantiate-an-array-of-objects-in-simpliest-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!