只要条件为
True
,就会在希望重复一组语句时使用
While...End While
结构。 如果希望更灵活地控制测试条件的位置或测试的结果,你可能更倾向使用
Do...Loop 语句
。 如果要将语句重复一组次数,则
For...Next Statement
通常是更好的选择。
While
关键字还在
Do...Loop 语句
、
Skip While 子句
和
Take While 子句
中使用。
如果
condition
为
True
,则在遇到
statements
语句之前运行所有
End While
。 控制随后会返回到
While
语句,并再次检查
condition
。 如果
condition
仍为
True
,则将重复该过程。 如果为
False
,则控制将传递给
End While
语句后面的语句。
While
语句在开始循环之前始终检查条件。 当条件为
True
时,循环将继续。 首次输入循环时,如果
condition
是
False
,则一次都不会运行。
condition
通常是由两个值比较导致的,但它可以是计算结果为
布尔数据类型
值(
True
或
False
)的任何表达式。 此表达式可以包括已转换为
Boolean
的其他数据类型(如数值类型)的值。
可以通过将 1 个循环放入另一个循环来嵌套
While
循环。 还可以在彼此之间嵌套不同种类的控制结构。 有关详细信息,请参阅
嵌套控制结构
。
Exit While
Exit While
语句可以提供退出
While
循环的替代方法。
Exit While
立即将控制转移到
End While
语句后面的语句。
通常在计算某些条件后(例如在
If...Then...Else
结构中)使用
Exit While
。 如果检测到可能导致不必要或无法继续迭代的条件(如错误值或终止请求),则可能需要退出循环。 测试可能导致无限循环的情况时可以使用
Exit While
,这是可运行很大甚至无限次数的循环。 然后,可以使用
Exit While
来转义循环。
可以将任意数量的
Exit While
语句置于
While
循环中的任意位置。
在嵌套
While
循环内使用时,
Exit While
将控制转移出最内层循环,并将其转移到下一个更高级别的嵌套。
Continue While
语句立即将控制转移到循环的下一次迭代。 有关详细信息,请参阅
Continue 语句
。
在下面的示例中,循环中的语句将继续运行,直到
index
变量大于 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
下面的示例阐释了 Continue While 和 Exit While 语句的用法。
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
下面的示例读取文本文件中的所有行。 OpenText 方法打开文件并返回读取字符的 StreamReader。 在 While 条件中,StreamReader 的 Peek 方法确定文件是否包含其他字符。
Private Sub ShowText(ByVal textFilePath As String)
If System.IO.File.Exists(textFilePath) = False Then
Debug.WriteLine("File Not Found: " & textFilePath)
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
Do...Loop 语句
For...Next 语句
Boolean 数据类型
嵌套的控件结构
Exit 语句
Continue 语句