以最简单的方式实例化对象数组?
给定一个类:
class clsPerson { public int x, y; }
是否有某种方法可以创建这些类的数组,其中每个元素都初始化为(默认)构造实例,而无需在 for 循环中手动执行此操作,例如:
clsPerson[] objArr = new clsPerson[1000];
for (int i = 0; i < 1000; ++i)
objArr[i] = new clsPerson();
我可以缩短 N 个对象数组的声明和实例化吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,必须为数组中的每个项目运行构造函数。无论您是否使用循环、集合初始值设定项或辅助方法,都必须访问数组中的每个元素。
如果您只是在寻找一种方便的语法,那么您可以使用以下内容
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
您必须为每个项目调用构造函数。如果不构造每个项目,则无法分配数组并在项目上调用类构造函数。
您可以使用以下方法从循环中缩短它(一点点):
就我个人而言,我仍然会分配数组并循环遍历它(和/或将其移动到辅助例程中),因为它非常清晰并且仍然相当简单:
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:
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:
如果这样做有意义,您可以将
class clsPerson
更改为struct Person
。struct
总是有一个默认值。If it would make sense to do so, you could change
class clsPerson
tostruct Person
.struct
s always have a default value.