实例化数组并立即实例化每个成员
考虑以下情况:
ColumnDefinition[] columns = new ColumnDefinition[2];
columns[0] = new ColumnDefinition();
columns[1] = new ColumnDefinition();
将列实例化为 ColumnDefinition 数组后,我需要显式实例化每个数组元素。当然,它可以使用循环来完成,但我想知道是否有更简单的方法可以在实例化数组类型本身之后立即实例化每个元素。
Consider the following case:
ColumnDefinition[] columns = new ColumnDefinition[2];
columns[0] = new ColumnDefinition();
columns[1] = new ColumnDefinition();
After instantiating columns as an array of ColumnDefinition, I needed to explicitly instantiate each array element. Of course, it could have been done using loops, but I was wondering if there was something simpler which would instantiate every element at once after instantiating the Array type itself.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以应用一点 LINQ:
调整传递给
Repeat
为数组的大小。然而,这将导致相同的对象被保存在数组的每个元素中。所以也许需要重复创建:You can apply a little LINQ:
Adjust the count passed to
Repeat
for the size of array. However this will lead to the same object being saved in each element of the array. So maybe the creation needs to be repeated:按预期工作。
Works as expected.
据我所知,任何使用除简单
for
循环以外的解决方案都会产生可怕的性能,而且for
循环无论如何也只需要 3 行。As far as I know, any solution using anything other than a simple
for
loop for this will have a horrible performance and afor
loop would only take 3 lines anyway.您可以使用 Array.Initialize 方法
通过调用值类型的默认构造函数来初始化值类型数组的每个元素。
You can use Array.Initialize Method
Initializes every element of the value-type Array by calling the default constructor of the value type.