For Each...Next 语句
来源:互联网 发布:淘宝搜索排除关键字 编辑:程序博客网 时间:2024/05/17 03:42
For Each...Next 语句 (Visual Basic)
更新: 2008 年 7 月
对于集合中的每个元素重复一组语句。
For Each element [ As datatype ] In group [ statements ] [ Exit For ] [ statements ]Next [ element ]
当需要为集合或数组的每个元素重复执行一组语句时,请使用 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 属性以及 Reset 和 MoveNext 方法。Visual Basic 使用它们遍历集合。
group 的元素通常属于 Object 类型,但是可以拥有任何运行时数据类型。
收缩转换。当 Option Strict 设置为 On 时,收缩转换通常会导致编译器错误。在下面的示例中,当 Option Strict 设置为 on 时,不会对将 m 赋为 n 的初始值的赋值语句进行编译,因为从 Long 到 Integer 的转换是收缩转换。
VBDim m As Long = 987' Does not compile.'Dim n As Integer = m
但是,会在运行时计算并执行从 group 中的元素到 element 的转换,并禁止显示收缩转换错误。在下面的示例中,虽然要求使用从 Long 到 Integer 的相同转换(该转换在上一示例中导致了错误),也不会在 For Each 循环中报告任何编译器错误。
VBOption 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
- For Each...Next 语句
- For Each...Next 语句
- 浅析VB For Each.Next语句
- VBS基础篇 - 循环语句(4) - For Each...Next
- Java for each语句
- for-each 语句
- vb.net 教程 2-4 流程控制:循环语句 For each...Next
- Java中for-each语句
- java中for each语句的使用
- as3中for..in 语句和for each..in 语句
- as3中for..in 语句和for each..in 语句
- as3中for..in 语句和for each..in 语句
- ASP中For…Next循环语句
- 理解 for..in 和 for each..in 语句
- for...in和for each...in语句遍历
- for each
- for each
- for each
- java连接mysql
- 浮点数总结
- 复习Java基础2_2(2011 06 11)
- Mysql 百万级数据优化资料
- To extend jQuery function for gloable usage
- For Each...Next 语句
- java 控制台输入数字..并排序
- google Map 学习
- css--百度百科
- Pad application for ordering (应用之酒店点菜系统)
- 转战CSDN
- action中 读取 form, 空值情况
- CVS 百度百科
- Why VHD not working on my Kingston UFD