Instantiate an array of objects, in simpliest way?

后端 未结 3 2226
傲寒
傲寒 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:20

    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(); 
    

提交回复
热议问题