以最简单的方式实例化对象数组? [英] Instantiate an array of objects, in simpliest way?

查看:86
本文介绍了以最简单的方式实例化对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上课:

class clsPerson { public int x, y; }

是否有某种方法可以创建这些类的数组,并将每个元素初始化为(默认)构造的实例,而无需在for循环中手动进行操作,例如:

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

我可以缩短N个对象数组的声明和实例化吗?

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

推荐答案

您必须为每个项目调用构造函数.如果不构造每个项目,就无法分配数组并在项目上调用类构造函数.

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

这篇关于以最简单的方式实例化对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆