默认情况下,引用类型数组初始化,所有引用都为null。
是否有任何语法技巧可以用新的默认对象初始化它们?
例如
public class Child
{
}
public class Parent
{
private Child[] _children = new Child[10];
public Parent()
{
//any way to negate the need for this?
for (int n = 0; n < _children.Length; n++)
_children[n] = new Child();
}
}
答案 0 :(得分:6)
使用LINQ:
private Child[] _children = Enumerable
.Range(1, 10)
.Select(i => new Child())
.ToArray();
答案 1 :(得分:3)
你可以使用object and collection initializers,虽然您的版本可能更简洁,可以用于更大的集合:
private Child[] _children = new Child[] {
new Child(),
new Child(),
new Child(),
new Child(),
new Child(),
new Child(),
new Child(),
new Child(),
new Child()
};
答案 2 :(得分:0)
即使你的for循环看起来比漂亮的LINQ语句更糟糕,它的运行时行为也会快得多。例如。在数组中使用20个Form的测试是0.7(for loop)到3.5(LINQ)毫秒