通常,不能调用具有比过程声明指定的参数更多的过程。 当需要无限数量的参数时,可以声明 参数数组,这允许过程接受参数的值数组。 定义过程时,不必知道参数数组中的元素数。 数组大小由对过程的每个调用单独确定。
声明 ParamArray
可以使用 ParamArray 关键字来表示参数列表中的参数数组。 下列规则适用:
过程只能定义一个参数数组,并且它必须是过程定义中的最后一个参数。
参数数组必须按值传递。 在过程定义中显式包含 ByVal 关键字是很好的编程做法。
参数数组是自动可选的。 其默认值是参数数组的元素类型的空一维数组。
参数数组之前的所有参数都是必需的。 参数数组必须是唯一的可选参数。
调用 ParamArray
调用定义参数数组的过程时,可以通过以下任一方式提供参数:
无 - 也就是说,可以省略 ParamArray 参数。 在这种情况下,将空数组传递给该过程。 如果显式传递 Nothing 关键字,则会将 null 数组传递给该过程,如果调用的过程未检查此条件,则可能会导致 NullReferenceException。
任意数量的自变量的列表,用逗号分隔。 每个参数的数据类型必须隐式转换为
ParamArray
元素类型。与参数数组的元素类型相同的数组。
在所有情况下,过程中的代码将参数数组视为具有与 ParamArray
数据类型相同元素类型的一维数组。
重要
每当处理可能无限大的数组时,都会有溢出应用程序的某些内部容量的风险。 如果接受参数数组,则应测试调用代码传递给它的数组的大小。 如果某个元素对您的应用程序来说太大,请执行相应的步骤。 有关详细信息,请参阅 array。
示例:
下面的示例定义并调用函数 calcSum
。 参数 ParamArray
的 args
修饰符使函数能够接受可变数量的参数。
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)