VB.Net - 函数

过程是一组调用时一起执行任务的语句。执行该过程之后,控制返回到调用过程的语句。 VB.Net有两种类型的程序:

  • Functions

函数返回一个值,而Subs不返回值。

定义函数

函数语句用于声明函数的名称,参数和主体。 函数语句的语法是:

[Modifiers] Function FunctionName [(ParameterList)] As ReturnType [Statements] End Function

  • Modifiers 修饰符 :指定函数的访问级别;可能的值有:公共,私有,保护,朋友,关于保护超载,重载,共享和阴影朋友和信息。

示例

以下代码片段显示了一个函数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 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