只是將返回值設置為函數名仍然與Java(或其他)語句不完全相同return
,因為在java中,return
退出函數,如下所示:
public int test(int x) {
if (x == 1) {
return 1; // exits immediately
}
// still here? return 0 as default.
return 0;}
在VB中,如果未在函數末尾設置返回值,則精確等效項需要兩行。因此,在VB中,確切的推論看起來像這樣:
Public Function test(ByVal x As Integer) As Integer
If x = 1 Then
test = 1 ' does not exit immediately. You must manually terminate...
Exit Function ' to exit
End If
' Still here? return 0 as default.
test = 0
' no need for an Exit Function because we're about to exit anyway.End Function
既然如此,那么知道你可以像使用方法中的任何其他變量一樣使用return變量也是很好的。像這樣:
Public Function test(ByVal x As Integer) As Integer
test = x ' <-- set the return value
If test <> 1 Then ' Test the currently set return value
test = 0 ' Reset the return value to a *new* value
End IfEnd Function
或者,返回變量如何工作的極端例子(但不一定是你應該如何實際編碼的一個很好的例子) - 那個會讓你夜不能寐的一個例子:
Public Function test(ByVal x As Integer) As Integer
test = x ' <-- set the return value
If test > 0 Then
' RECURSIVE CALL...WITH THE RETURN VALUE AS AN ARGUMENT,
' AND THE RESULT RESETTING THE RETURN VALUE.
test = test(test - 1)
End IfEnd Function