Istruzione Do...Loop (Visual Basic)Do...Loop Statement (Visual Basic)
Ripete un blocco di istruzioni mentre una Boolean
condizione è True
o finché la condizione non diventa True
.Repeats a block of statements while a Boolean
condition is True
or until the condition becomes True
.
SintassiSyntax
Do { While | Until } condition
[ statements ]
[ Continue Do ]
[ statements ]
[ Exit Do ]
[ statements ]
Loop
' -or-
Do
[ statements ]
[ Continue Do ]
[ statements ]
[ Exit Do ]
[ statements ]
Loop { While | Until } condition
PartiParts
TermineTerm | DefinizioneDefinition |
---|---|
Do |
Obbligatorio.Required. Avvia la definizione del Do ciclo.Starts the definition of the Do loop. |
While |
Obbligatorio a meno che non sia usato Until .Required unless Until is used. Ripetere il ciclo finché non condition è False .Repeat the loop until condition is False . |
Until |
Obbligatorio a meno che non sia usato While .Required unless While is used. Ripetere il ciclo finché non condition è True .Repeat the loop until condition is True . |
condition |
facoltativo.Optional. Espressione Boolean .Boolean expression. Se condition è Nothing , Visual Basic lo considera come False .If condition is Nothing , Visual Basic treats it as False . |
statements |
facoltativo.Optional. Una o più istruzioni ripetute durante o fino a condition True .One or more statements that are repeated while, or until, condition is True . |
Continue Do |
facoltativo.Optional. Trasferisce il controllo all'iterazione successiva del Do ciclo.Transfers control to the next iteration of the Do loop. |
Exit Do |
facoltativo.Optional. Trasferisce il controllo all'esterno del Do ciclo.Transfers control out of the Do loop. |
Loop |
Obbligatorio.Required. Termina la definizione del Do ciclo.Terminates the definition of the Do loop. |
CommentiRemarks
Utilizzare una Do...Loop
struttura quando si desidera ripetere un set di istruzioni un numero indefinito di volte, fino a quando non viene soddisfatta una condizione.Use a Do...Loop
structure when you want to repeat a set of statements an indefinite number of times, until a condition is satisfied. Se si desidera ripetere le istruzioni impostando il numero di volte, per... L'istruzione successiva è in genere una scelta migliore.If you want to repeat the statements a set number of times, the For...Next Statement is usually a better choice.
È possibile utilizzare While
o Until
per specificare condition
, ma non entrambi.You can use either While
or Until
to specify condition
, but not both.
È possibile eseguire il test condition
solo una volta, sia all'inizio che alla fine del ciclo.You can test condition
only one time, at either the start or the end of the loop. Se si verifica condition
all'inizio del ciclo (nell' Do
istruzione), il ciclo potrebbe non essere eseguito neanche una volta.If you test condition
at the start of the loop (in the Do
statement), the loop might not run even one time. Se si esegue il test alla fine del ciclo (nell' Loop
istruzione), il ciclo viene sempre eseguito almeno una volta.If you test at the end of the loop (in the Loop
statement), the loop always runs at least one time.
La condizione viene in genere generata da un confronto di due valori, ma può essere qualsiasi espressione che restituisce un valore booleano di tipo di dati ( True
o False
).The condition usually results from a comparison of two values, but it can be any expression that evaluates to a Boolean Data Type value (True
or False
). Sono inclusi i valori di altri tipi di dati, ad esempio i tipi numerici, che sono stati convertiti in Boolean
.This includes values of other data types, such as numeric types, that have been converted to Boolean
.
È possibile annidare Do
cicli inserendo un ciclo all'interno di un altro.You can nest Do
loops by putting one loop within another. È anche possibile annidare diversi tipi di strutture di controllo tra loro.You can also nest different kinds of control structures within each other. Per altre informazioni, vedere strutture di controlli annidati.For more information, see Nested Control Structures.
Nota
La Do...Loop
struttura offre una maggiore flessibilità rispetto al tempo... End While , perché consente di decidere se terminare il ciclo quando viene condition
interrotto True
o quando diventa prima True
.The Do...Loop
structure gives you more flexibility than the While...End While Statement because it enables you to decide whether to end the loop when condition
stops being True
or when it first becomes True
. Consente inoltre di eseguire il test condition
sia all'inizio che alla fine del ciclo.It also enables you to test condition
at either the start or the end of the loop.
Esci da doExit Do
L'istruzione Exit Do può fornire un metodo alternativo per uscire da Do…Loop
.The Exit Do statement can provide an alternative way to exit a Do…Loop
. Exit Do
trasferisce immediatamente il controllo all'istruzione che segue l' Loop
istruzione.Exit Do
transfers control immediately to the statement that follows the Loop
statement.
Exit Do
viene spesso usato dopo la valutazione di una determinata condizione, ad esempio in una If...Then...Else
struttura.Exit Do
is often used after some condition is evaluated, for example in an If...Then...Else
structure. Potrebbe essere necessario uscire da un ciclo se viene rilevata una condizione che rende superfluo o Impossibile continuare l'iterazione, ad esempio un valore errato o una richiesta di terminazione.You might want to exit a loop if you detect a condition that makes it unnecessary or impossible to continue iterating, such as an erroneous value or a termination request. Un uso di Exit Do
è quello di verificare la presenza di una condizione che può causare un ciclo infinito, ovvero un ciclo che può eseguire un numero di volte elevato o infinito.One use of Exit Do
is to test for a condition that could cause an endless loop, which is a loop that could run a large or even infinite number of times. È possibile utilizzare Exit Do
per eseguire l'escape del ciclo.You can use Exit Do
to escape the loop.
È possibile includere qualsiasi numero di Exit Do
istruzioni in un punto qualsiasi di un oggetto Do…Loop
.You can include any number of Exit Do
statements anywhere in a Do…Loop
.
Quando viene utilizzato all'interno Do
di cicli annidati, Exit Do
trasferisce il controllo al di fuori del ciclo più interno e al successivo livello di nidificazione.When used within nested Do
loops, Exit Do
transfers control out of the innermost loop and into the next higher level of nesting.
EsempioExample
Nell'esempio seguente, le istruzioni del ciclo continuano a essere eseguite fino a quando la index
variabile non è maggiore di 10.In the following example, the statements in the loop continue to run until the index
variable is greater than 10. La Until
clausola si trova alla fine del ciclo.The Until
clause is at the end of the loop.
Dim index As Integer = 0
Do
Debug.Write(index.ToString & " ")
index += 1
Loop Until index > 10
Debug.WriteLine("")
' Output: 0 1 2 3 4 5 6 7 8 9 10
EsempioExample
Nell'esempio seguente viene utilizzata una While
clausola anziché una Until
clausola e condition
viene testato all'inizio del ciclo anziché alla fine.The following example uses a While
clause instead of an Until
clause, and condition
is tested at the start of the loop instead of at the end.
Dim index As Integer = 0
Do While index <= 10
Debug.Write(index.ToString & " ")
index += 1
Loop
Debug.WriteLine("")
' Output: 0 1 2 3 4 5 6 7 8 9 10
EsempioExample
Nell'esempio seguente, condition
Arresta il ciclo quando la index
variabile è maggiore di 100.In the following example, condition
stops the loop when the index
variable is greater than 100. Nell' If
istruzione del ciclo, tuttavia, l' Exit Do
istruzione arresta il ciclo quando la variabile di indice è maggiore di 10.The If
statement in the loop, however, causes the Exit Do
statement to stop the loop when the index variable is greater than 10.
Dim index As Integer = 0
Do While index <= 100
If index > 10 Then
Exit Do
End If
Debug.Write(index.ToString & " ")
index += 1
Loop
Debug.WriteLine("")
' Output: 0 1 2 3 4 5 6 7 8 9 10
EsempioExample
Nell'esempio seguente vengono lette tutte le righe in un file di testo.The following example reads all lines in a text file. Il OpenText metodo apre il file e restituisce un oggetto StreamReader che legge i caratteri.The OpenText method opens the file and returns a StreamReader that reads the characters. Nella Do...Loop
condizione, il Peek metodo di StreamReader
determina se sono presenti caratteri aggiuntivi.In the Do...Loop
condition, the Peek method of the StreamReader
determines whether there are any additional characters.
Private Sub ShowText(ByVal textFilePath As String)
If System.IO.File.Exists(textFilePath) = False Then
Debug.WriteLine("File Not Found: " & textFilePath)
Else
Dim sr As System.IO.StreamReader = System.IO.File.OpenText(textFilePath)
Do While sr.Peek() >= 0
Debug.WriteLine(sr.ReadLine())
Loop
sr.Close()
End If
End Sub