For Each...Next 语句

来源:互联网 发布:淘宝搜索排除关键字 编辑:程序博客网 时间:2024/05/17 03:42

For Each...Next 语句 (Visual Basic)

Visual Studio 2008

 

更新: 2008 年 7 月

对于集合中的每个元素重复一组语句。

For Each element [ As datatype ] In group    [ statements ]    [ Exit For ]    [ statements ]Next [ element ]
各部分说明

element

For Each 语句中是必选项。在 Next 语句中是可选项。变量。用于循环访问集合的元素。

datatype

如果尚未声明 element,则是必选项。element 的数据类型。

group

必需。对象变量。引用要重复 statements 的集合。

statements

可选。For EachNext 之间的一条或多条语句,这些语句在 group 中的每一项上运行。

Exit For

可选。将控制转移到 For Each 循环外。

Next

必需。终止 For Each 循环的定义。

备注

当需要为集合或数组的每个元素重复执行一组语句时,请使用 For Each...Next 循环。

当可以将循环的每次迭代与控制变量相关联并可确定该变量的初始值和最终值时,For...Next 语句 (Visual Basic) 非常适合。但是,在处理集合时,初始值和最终值的概念没有意义,而且您不必知道集合中包含多少元素。在这种情况下,For Each...Next 循环是一个更好的选择。

规则

  • 数据类型。group 的元素的数据类型必须可以转换为 element 的数据类型。

    group 的数据类型必须是引用集合或数组的引用类型。这意味着 group 必须引用实现 System.Collections 命名空间的 IEnumerable 接口或 System.Collections.Generic 命名空间的 IEnumerable(Of T) 接口的对象。IEnumerable 定义 GetEnumerator 方法,而该方法返回集合的枚举数对象。枚举数对象实现 System.Collections 命名空间的 IEnumerator 接口,并公开 Current 属性以及 ResetMoveNext 方法。Visual Basic 使用它们遍历集合。

    group 的元素通常属于 Object 类型,但是可以拥有任何运行时数据类型。

  • 收缩转换。Option Strict 设置为 On 时,收缩转换通常会导致编译器错误。在下面的示例中,当 Option Strict 设置为 on 时,不会对将 m 赋为 n 的初始值的赋值语句进行编译,因为从 LongInteger 的转换是收缩转换。

     
    VB
     
    Dim m As Long = 987' Does not compile.'Dim n As Integer = m

    但是,会在运行时计算并执行从 group 中的元素到 element 的转换,并禁止显示收缩转换错误。在下面的示例中,虽然要求使用从 LongInteger 的相同转换(该转换在上一示例中导致了错误),也不会在 For Each 循环中报告任何编译器错误。

     
    VB
     
    Option Strict OnModule Module1    Sub Main()        ' The assignment of m to n causes a compiler error when         ' Option Strict is on.        Dim m As Long = 987        'Dim n As Integer = m        ' The For Each loop requires the same conversion, but        ' causes no errors. The output is 45 3 987.        For Each p As Integer In New Long() {45, 3, 987}            Console.Write(p & " ")        Next        Console.WriteLine()    End SubEnd Module