开发者

Instantiating Array and Instantiating each Member at once

Consider the following case:

ColumnDefinition[] columns = new ColumnDefinition[2];
columns[0] = new ColumnDefinition();
co开发者_开发技巧lumns[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.


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


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

Works as expected.


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


You can use Array.Initialize Method Initializes every element of the value-type Array by calling the default constructor of the value type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜