Basta impostare il valore di ritorno al nome della funzione non è ancora esattamente lo stesso del Java (o altro) return
dichiarazione, perché in java, return
esce la funzione, in questo modo:
public int test(int x) {
if (x == 1) {
return 1; // exits immediately
}
// still here? return 0 as default.
return 0;
}
In VB, l'equivalente esatto richiede due righe se non si imposta il valore restituito alla fine della funzione. Così, in VB corollario esatto sarebbe simile a questa:
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
Dal momento che questo è il caso, è anche bello sapere che è possibile utilizzare la variabile di ritorno come qualsiasi altra variabile nel metodo.Come questo:
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 If
End Function
Oppure, all'estremo esempio di come la variabile di ritorno funziona (ma non necessariamente un buon esempio di come si dovrebbe in realtà codice) -quello che vi terrà sveglio la notte:
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 If
End Function
Documentazione: http://msdn.microsoft.com/en-us/library/office/gg264233%28v=office.14%29.aspx –