正如我們在上一章中提到的,Sub過程是不返回任何值的過程。 我們在所有的例子中一直使用Sub過程Main。 到目前為止,我們已經(jīng)在這些教程中編寫控制臺應(yīng)用程序。 當(dāng)這些應(yīng)用程序開始時,控制轉(zhuǎn)到主子程序,它反過來運(yùn)行構(gòu)成程序主體的任何其他語句。
Sub語句用于聲明子過程的名稱,參數(shù)和主體。 Sub語句的語法是:
[Modifiers] Sub SubName [(ParameterList)] [Statements] End Sub
Modifiers 修飾符 :指定過程的訪問級別;可能的值有:Public, Private, Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing, and shadowing.
SubName 子名 :表示該子的名字
ParameterList 參數(shù)列表 :指定參數(shù)的列表
Sub CalculatePay(ByRef hours As Double, ByRef wage As Decimal) 'local variable declaration Dim pay As Double pay = hours * wage Console.WriteLine("Total Pay: {0:C}", pay) End Sub Sub Main() 'calling the CalculatePay Sub Procedure CalculatePay(25, 10) CalculatePay(40, 20) CalculatePay(30, 27.5) Console.ReadLine() End Sub End Module
當(dāng)上述代碼被編譯和執(zhí)行時,它產(chǎn)生了以下結(jié)果:
Total Pay: $250.00 Total Pay: $800.00 Total Pay: $825.00
這是將參數(shù)傳遞給方法的默認(rèn)機(jī)制。 在這種機(jī)制中,當(dāng)調(diào)用方法時,為每個值參數(shù)創(chuàng)建一個新的存儲位置。 實(shí)際參數(shù)的值被復(fù)制到它們中。 因此,對方法中的參數(shù)所做的更改對參數(shù)沒有影響。
在VB.Net中,可以使用ByVal關(guān)鍵字聲明引用參數(shù)。 下面的例子演示了這個概念:
Module paramByval Sub swap(ByVal x As Integer, ByVal y As Integer) Dim temp As Integer temp = x ' save the value of x x = y ' put y into x y = temp 'put temp into y End Sub Sub Main() ' local variable definition Dim a As Integer = 100 Dim b As Integer = 200 Console.WriteLine("Before swap, value of a : {0}", a) Console.WriteLine("Before swap, value of b : {0}", b) ' calling a function to swap the values ' swap(a, b) Console.WriteLine("After swap, value of a : {0}", a) Console.WriteLine("After swap, value of b : {0}", b) Console.ReadLine() End Sub End Module
當(dāng)上述代碼被編譯和執(zhí)行時,它產(chǎn)生了以下結(jié)果:
Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :100 After swap, value of b :200
它表明,雖然它們在函數(shù)內(nèi)部已更改,但值中沒有變化。
引用參數(shù)是對變量的存儲器位置的引用。 當(dāng)您通過引用傳遞參數(shù)時,與值參數(shù)不同,不會為這些參數(shù)創(chuàng)建新的存儲位置。 參考參數(shù)表示與提供給該方法的實(shí)際參數(shù)相同的存儲器位置。
在VB.Net中,可以使用ByRef關(guān)鍵字聲明引用參數(shù)。 以下示例演示了這一點(diǎn):
Module paramByref Sub swap(ByRef x As Integer, ByRef y As Integer) Dim temp As Integer temp = x ' save the value of x x = y ' put y into x y = temp 'put temp into y End Sub Sub Main() ' local variable definition Dim a As Integer = 100 Dim b As Integer = 200 Console.WriteLine("Before swap, value of a : {0}", a) Console.WriteLine("Before swap, value of b : {0}", b) ' calling a function to swap the values ' swap(a, b) Console.WriteLine("After swap, value of a : {0}", a) Console.WriteLine("After swap, value of b : {0}", b) Console.ReadLine() End Sub End Module
當(dāng)上述代碼被編譯和執(zhí)行時,它產(chǎn)生了以下結(jié)果:
Before swap, value of a : 100 Before swap, value of b : 200 After swap, value of a : 200 After swap, value of b : 100
更多建議: