參數陣列 (Visual Basic)

您通常無法呼叫引數的數量多於程序宣告所指定數量的程序。 需要無限個引數時,可以宣告參數陣列,這可讓程序接受參數的值陣列。 定義程序時,您不需要知道參數陣列中的元素數量。 陣列大小是由程序的每個呼叫分別決定。

宣告 ParamArray

您可以使用 ParamArray 關鍵字來表示參數清單中的參數陣列。 適用的規則如下:

  • 程序只能定義一個參數陣列,而且必須是程序定義中的最後一個參數。

  • 參數陣列必須以值傳遞。 在程序定義中明確包含 ByVal 關鍵字是很明智的程式設計做法。

  • 參數陣列為自動選擇性。 其預設值是參數陣列元素型別的空白一維陣列。

  • 參數陣列之前的所有參數都須為必要。 參數陣列必須是唯一的選擇性參數。

呼叫 ParamArray

呼叫定義參數陣列的程序時,您可以使用下列任一種方式來提供引數:

  • Nothing - 也就是可以省略 ParamArray 引數。 在此情況下,會將一個空陣列傳遞至程序。 如果您明確傳遞 Nothing 關鍵字,則會將 Null 陣列傳遞至程序,如果呼叫的程序未檢查此條件,可能會導致 NullReferenceException。

  • 任意數目的引數清單 (以逗號分隔)。 每個引數的資料型別都必須隱含轉換成 ParamArray 元素型別。

  • 元素型別與參數陣列相同的陣列。

在所有情況下,程序內的程式碼都會將參數陣列視為一維陣列,且具有資料型別與 ParamArray 相同的元素。

重要

每當您處理可能無限大的陣列時,都會有應用程式部分內部容量不足的風險。 如果您接受參數陣列,應該先測試呼叫程式碼傳遞給它的陣列大小。 如果對您的應用程式來說太大,請採取適當的步驟。 如需詳細資訊,請參閱陣列

範例

下列範例定義呼叫 calcSum 函式。 args 參數的 ParamArray 修飾元可讓函式接受數量可變動的引數。

Module Module1

    Sub Main()
        ' In the following function call, CalcSum's local variables
        ' are assigned the following values: args(0) = 4, args(1) = 3,
        ' and so on. The displayed sum is 10.
        Dim returnedValue As Double = CalcSum(4, 3, 2, 1)
        Console.WriteLine("Sum: " & returnedValue)
        ' Parameter args accepts zero or more arguments. The sum
        ' displayed by the following statements is 0.
        returnedValue = CalcSum()
        Console.WriteLine("Sum: " & returnedValue)
    End Sub

    Public Function CalcSum(ByVal ParamArray args() As Double) As Double
        CalcSum = 0
        If args.Length <= 0 Then Exit Function
        For i As Integer = 0 To UBound(args, 1)
            CalcSum += args(i)
        Next i
    End Function

End Module

下列範例定義具有參數陣列的程序,並輸出傳遞至參數陣列之所有陣列元素的值。

Sub studentScores(ByVal name As String, ByVal ParamArray scores() As String)
    Debug.WriteLine("Scores for " & name & ":" & vbCrLf)
    ' Use UBound to determine largest subscript of the array.
    For i As Integer = 0 To UBound(scores, 1)
        Debug.WriteLine("Score " & i & ": " & scores(i))
    Next i
End Sub
Call studentScores("Anne", "10", "26", "32", "15", "22", "24", "16")
Call studentScores("Mary", "High", "Low", "Average", "High")
Dim JohnScores() As String = {"35", "Absent", "21", "30"}
Call studentScores("John", JohnScores)

另請參閱