是否可以声明数组大小并在同一行中分配?

时间:2017-04-06 16:24:06

标签: c# arrays

是否可以声明数组的大小并将其分配给同一行中数组中的第一个元素?

var newRecord = new RecordModel
{
  Artist = "KRS-ONE",
  Title = "Return of the Boom Bap",
  Tracks = new int[NumberOfTracks] // Is there a way to assign here?
}

// Currently doing it this way
newRecord.Tracks[0] = 2;

2 个答案:

答案 0 :(得分:4)

您可以内联初始化数组大小和值,但必须设置其所有值

//This works
var numbers = new int[3]{1,2,3};

//This doesn't, "An array initializer of length '3' is expected"
var numbers = new int[3]{1};

答案 1 :(得分:1)

我认为最好使用一个列表。

var list = new List<int>() { 1, 2, 3 };