如何在VB.NET中将数组设置为值列表?

时间:2010-04-08 18:22:01

标签: vb.net arrays

我无法弄清楚如何将数组设置为两组数字中的一组(稍后会有更多),我尝试的每种方式都会引发某种错误。我试图在case语句中调暗数组,但后来我不能在For Each中使用数组,这使得它毫无价值......任何想法都会受到赞赏。

代码:

Dim HourArray() As Integer

Select Case CurrentShapeRow(ROW_PERIOD)
    Case "ON", "2X16"
        HourArray = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21}
    Case "2X8", "5X8"
        HourArray = {0, 1, 2, 3, 4, 5, 22, 23}
    Case Else
        Throw New Exception(String.Format("Unhandled Period: {0}", CurrentShapeRow(ROW_PERIOD)))
End Select


For Each HourCount As Integer In HourArray()
     'DO SOME STUFF HERE
Next

3 个答案:

答案 0 :(得分:5)

HourArray = New Integer() {1,2,3,4,5,6,7,8,9}

答案 1 :(得分:4)

将数组分配给现有变量时,必须明确使用构造函数:

HourArray = New Integer() { 6, 7, 8, 9, 10, 11, 12, 13 }

这与构造函数是可选的声明和赋值不同:

Dim HourArray() As Integer = { 6, 7, 8, 9, 10, 11, 12, 13 }

答案 2 :(得分:2)

    Dim hourArray As List(Of Integer)

    Select Case CurrentShapeRow(ROW_PERIOD)
        Case "ON", "2X16"
            hourArray.AddRange(New Integer() {6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21})
        Case "2X8", "5X8"
            hourArray.AddRange(New Integer() {0, 1, 2, 3, 4, 5, 22, 23})
        Case Else
            Throw New Exception(String.Format("Unhandled Period: {0}", CurrentShapeRow(ROW_PERIOD)))
    End Select

For Each i As Integer In hourArray
    Console.WriteLine(i)
Next