实例化数组并立即实例化每个成员

发布于 2024-11-08 13:05:38 字数 272 浏览 0 评论 0原文

考虑以下情况:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

紫﹏色ふ单纯 2024-11-15 13:05:38

您可以应用一点 LINQ:

var columns = Enumerable.Repeat(new ColumnDefinition(), 10).ToArray();

调整传递给 Repeat 为数组的大小。然而,这将导致相同的对象被保存在数组的每个元素中。所以也许需要重复创建:

var columns = Enumerable.Repeat(0, 10).Select(i => new ColumnDefinition()).ToArray();

You can apply a little LINQ:

var columns = Enumerable.Repeat(new ColumnDefinition(), 10).ToArray();

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:

var columns = Enumerable.Repeat(0, 10).Select(i => new ColumnDefinition()).ToArray();
江城子 2024-11-15 13:05:38
var columns = new []{new ColumnDefinition(), new ColumnDefinition()};

按预期工作。

var columns = new []{new ColumnDefinition(), new ColumnDefinition()};

Works as expected.

潦草背影 2024-11-15 13:05:38

据我所知,任何使用除简单 for 循环以外的解决方案都会产生可怕的性能,而且 for 循环无论如何也只需要 3 行。

var columns = new ColumnDefinition[2];
for (int i = 0; i <= columns.Count(); i++) {
    columns[i] = new ColumnDefinition();
}

// This is also a shorthand which compiles to above but only valid for types with
// default contructor as above (i.e. string[] array cannot be initialized with this)
columns.Initialize();

As far as I know, any solution using anything other than a simple for loop for this will have a horrible performance and a for loop would only take 3 lines anyway.

var columns = new ColumnDefinition[2];
for (int i = 0; i <= columns.Count(); i++) {
    columns[i] = new ColumnDefinition();
}

// This is also a shorthand which compiles to above but only valid for types with
// default contructor as above (i.e. string[] array cannot be initialized with this)
columns.Initialize();
我一向站在原地 2024-11-15 13:05:38

您可以使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文