Gaz*_*yer 5 c# arrays reference array-initialization
默认情况下,引用类型数组初始化,所有引用都为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();
}
}
Run Code Online (Sandbox Code Playgroud)
使用LINQ:
private Child[] _children = Enumerable
.Range(1, 10)
.Select(i => new Child())
.ToArray();
Run Code Online (Sandbox Code Playgroud)