• 07/20/2015
  • Чтение занимает 3 мин

В этой статье

Выполняет последовательность операторов, если заданное условие имеет значение True .Runs a series of statements as long as a given condition is True.

СинтаксисSyntax

While condition
[ statements ]
[ Continue While ]
[ statements ]
[ Exit While ]
[ statements ]
End While

КомпонентыParts

ТерминTermОпределениеDefinition
conditionОбязательный.Required. Выражение Boolean.Boolean expression. Если condition имеет значение Nothing , Visual Basic обрабатывает его как False .If condition is Nothing, Visual Basic treats it as False.
statementsНеобязательный элемент.Optional. Один или несколько следующих инструкций While , которые выполняются каждый раз, condition — True .One or more statements following While, which run every time condition is True.
Continue WhileНеобязательный элемент.Optional. Передает управление следующей итерации While блока.Transfers control to the next iteration of the While block.
Exit WhileНеобязательный элемент.Optional. Передает управление за пределы While блока.Transfers control out of the While block.
End WhileОбязательный элемент.Required. Завершает определение блока While.Terminates the definition of the While block.

Используйте While…End While структуру, если необходимо повторить набор инструкций неопределенное количество раз, если условие остается True .Use a While…End While structure when you want to repeat a set of statements an indefinite number of times, as long as a condition remains True. Если вы хотите обеспечить большую гибкость при тестировании условия или результата тестирования, вы можете предпочесть оператору Do… Loop, инструкция.If you want more flexibility with where you test the condition or what result you test it for, you might prefer the Do…Loop Statement. Если нужно повторить инструкции заданное число раз, то для… Обычно лучше подходит следующий оператор.If you want to repeat the statements a set number of times, the For…Next Statement is usually a better choice.

Если condition имеет значение True , все statements выполняется до тех пор, пока End While не будет обнаружен оператор.If condition is True, all of the statements run until the End While statement is encountered. Затем элемент управления возвращается в While инструкцию и condition снова проверяется.Control then returns to the While statement, and condition is again checked. Если condition по-прежнему True , процесс повторяется.If condition is still True, the process is repeated. Если это так False , управление передается оператору, следующему за End While оператором.If it’s False, control passes to the statement that follows the End While statement.

WhileОператор всегда проверяет условие перед началом цикла.The While statement always checks the condition before it starts the loop. Цикл продолжается, пока условие остается True .Looping continues while the condition remains True. Если параметр condition имеет значение False при первом входе в цикл, он не выполняется даже один раз.If condition is False when you first enter the loop, it doesn’t run even once.

conditionОбычно результат сравнения двух значений, но может быть любым выражением, результатом вычисления которого является логическое значение типа данных ( True или 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). Это выражение может включать в себя значение другого типа данных, например числовой тип, который был преобразован в Boolean .This expression can include a value of another data type, such as a numeric type, that has been converted to Boolean.

Можно вложить While циклы, поместив один цикл в другой.You can nest While loops by placing one loop within another. Можно также вкладывать различные виды управляющих структур друг в друга.You can also nest different kinds of control structures within one another. Дополнительные сведения см. в разделе вложенные структуры управления.For more information, see Nested Control Structures.

Выйти, покаExit While

Оператор Exit While может предоставить другой способ выхода из While цикла.The Exit While statement can provide another way to exit a While loop. Exit While немедленно передает управление оператору, который следует за End While оператором.Exit While immediately transfers control to the statement that follows the End While statement.

Обычно используется Exit While после вычисления некоторого условия (например, в If…Then…Else структуре).You typically use Exit While after some condition is evaluated (for example, in an If…Then…Else structure). Может потребоваться выйти из цикла, если обнаруживается условие, которое делает ненужным или невозможным продолжение итераций, например ошибочное значение или запрос на завершение.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. Можно использовать Exit While при проверке условия, которое может вызвать бесконечный цикл, что является циклом, который может выполнять очень большое или даже бесконечное число раз.You can use Exit While when you test for a condition that could cause an endless loop, which is a loop that could run an extremely large or even infinite number of times. Затем можно использовать Exit While для экранирования цикла.You can then use Exit While to escape the loop.

Любое количество операторов можно разместить Exit While в любом месте While цикла.You can place any number of Exit While statements anywhere in the While loop.

При использовании внутри вложенных While циклов Exit While передает управление за пределы самого внутреннего цикла и в следующий более высокий уровень вложенности.When used within nested While loops, Exit While transfers control out of the innermost loop and into the next higher level of nesting.

Continue WhileОператор немедленно передает управление следующей итерации цикла.The Continue While statement immediately transfers control to the next iteration of the loop. Дополнительные сведения см. в разделе оператор continue.For more information, see Continue Statement.

Читайте также:  Урсула ле гуин книги из цикла земноморье

ПримерExample

В следующем примере операторы в цикле продолжают выполняться до тех пор, пока index переменная не будет больше 10.In the following example, the statements in the loop continue to run until the index variable is greater than 10.

Dim index As Integer = 0
While index <= 10
Debug.Write(index.ToString & ” “)
index += 1
End While

Debug.WriteLine(“”)
‘ Output: 0 1 2 3 4 5 6 7 8 9 10

ПримерExample

В следующем примере показано использование Continue While Exit While операторов и.The following example illustrates the use of the Continue While and Exit While statements.

Dim index As Integer = 0
While index < 100000
index += 1

‘ If index is between 5 and 7, continue
‘ with the next iteration.
If index >= 5 And index <= 8 Then
Continue While
End If

‘ Display the index.
Debug.Write(index.ToString & ” “)

‘ If index is 10, exit the loop.
If index = 10 Then
Exit While
End If
End While

Debug.WriteLine(“”)
‘ Output: 1 2 3 4 9 10

ПримерExample

В следующем примере считываются все строки в текстовом файле.The following example reads all lines in a text file. OpenTextМетод открывает файл и возвращает объект StreamReader , считывающий символы.The OpenText method opens the file and returns a StreamReader that reads the characters. В While условии Peek метод StreamReader определяет, содержит ли файл дополнительные символы.In the While condition, the Peek method of the StreamReader determines whether the file contains 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)

While sr.Peek() >= 0
Debug.WriteLine(sr.ReadLine())
End While

sr.Close()
End If
End Sub

См. такжеSee also

  • Циклические структурыLoop Structures
  • Оператор Do…LoopDo…Loop Statement
  • Оператор For…NextFor…Next Statement
  • Логический тип данныхBoolean Data Type
  • Вложенные структуры управленияNested Control Structures
  • Оператор ExitExit Statement
  • Оператор ContinueContinue Statement