有时,在声明函数或子过程时,您不确定作为参数传递的参数的数量。 VB.Net param数组(或参数数组)在这些时候来帮助。
以下示例演示了这一点:
Module myparamfunc Function AddElements(ParamArray arr As Integer()) As Integer Dim sum As Integer = 0 Dim i As Integer = 0 For Each i In arr sum += i Next i Return sum End Function Sub Main() Dim sum As Integer sum = AddElements(512, 720, 250, 567, 889) Console.WriteLine("The sum is: {0}", sum) Console.ReadLine() End Sub End Module
当上述代码被编译和执行时,它产生了以下结果:
The sum is: 2938
您可以在VB.Net中将数组作为函数参数传递。 以下示例演示了这一点:
Module arrayParameter Function getAverage(ByVal arr As Integer(), ByVal size As Integer) As Double 'local variables Dim i As Integer Dim avg As Double Dim sum As Integer = 0 For i = 0 To size - 1 sum += arr(i) Next i avg = sum / size Return avg End Function Sub Main() ' an int array with 5 elements ' Dim balance As Integer() = {1000, 2, 3, 17, 50} Dim avg As Double 'pass pointer to the array as an argument avg = getAverage(balance, 5) ' output the returned value ' Console.WriteLine("Average value is: {0} ", avg) Console.ReadLine() End Sub End Module
当上述代码被编译和执行时,它产生了以下结果:
Average value is: 214.4
网站声明:如果转载,请联系本站管理员。否则一切后果自行承担。
添加我为好友,拉您入交流群!
请使用微信扫一扫!