VB.Net 函数
-
函数
过程是一组语句,它们在被调用时一起执行任务。执行过程后,控件返回到调用该过程的语句。VB.Net有两种类型的程序-- 函数
- 子程序或子程序
函数返回值,而子程序不返回值。 -
定义函数
Function 语句用于声明函数的名称,参数和主体。Function语句的语法是-[Modifiers] Function FunctionName [(ParameterList)] As ReturnType [Statements] End Function
说明- Modifiers - 指定函数的访问级别;可能的值包括:“Public”,“Private”,“Protected”,“Friend”,“Protected Friend”以及有关重载,覆盖,共享和映射的信息。
- FunctionName - 指示函数的名称
- ParameterList - 指定参数列表
- ReturnType - 指定函数返回的变量的数据类型
示例以下代码段显示了一个函数FindMax,该函数采用两个整数值并返回两个中较大的一个。Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer ' local variable declaration */ Dim result As Integer If (num1 > num2) Then result = num1 Else result = num2 End If FindMax = result End Function
-
函数返回值
在VB.Net中,函数可以通过两种方式将值返回到调用代码-- 通过使用return语句
- 通过将值分配给函数名称
以下示例演示如何使用FindMax函数-
尝试一下Module myfunctions Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer ' local variable declaration */ Dim result As Integer If (num1 > num2) Then result = num1 Else result = num2 End If FindMax = result End Function Sub Main() Dim a As Integer = 100 Dim b As Integer = 200 Dim res As Integer res = FindMax(a, b) Console.WriteLine("Max value is : {0}", res) Console.ReadLine() End Sub End Module
编译并执行上述代码后,将产生以下结果-Max value is : 200
-
递归函数
一个函数可以调用自己。这称为递归。以下是使用递归函数为给定数字计算阶乘的示例-
尝试一下Module myfunctions Function factorial(ByVal num As Integer) As Integer ' local variable declaration */ Dim result As Integer If (num = 1) Then Return 1 Else result = factorial(num - 1) * num Return result End If End Function Sub Main() 'calling the factorial method Console.WriteLine("Factorial of 6 is : {0}", factorial(6)) Console.WriteLine("Factorial of 7 is : {0}", factorial(7)) Console.WriteLine("Factorial of 8 is : {0}", factorial(8)) Console.ReadLine() End Sub End Module
编译并执行上述代码后,将产生以下结果-Factorial of 6 is: 720 Factorial of 7 is: 5040 Factorial of 8 is: 40320
-
参数数组
有时,在声明函数或子过程时,您不确定作为参数传递的参数数量。VB.Net参数数组(或参数数组)在这些时候起作用。以下示例演示了这一点-
尝试一下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