VB For Each循环示例

VB 的For Each循环用起来还挺顺手的,适合你在数组或集合的时候少写点代码,多干点事。它最大的特点就是不用管索引,直接拿数据用,省事。

遍历数组就常见啦,像下面这样:

Dim myArray As Integer() = {1, 2, 3, 4, 5}
For Each num In myArray
  Console.WriteLine(num)
Next num

是不是看着就挺清爽?遍历集合,比如List,也同样简单:

Dim myList As New List(Of String) From {"Apple", "Banana", "Cherry"}
For Each fruit In myList
  Console.WriteLine(fruit)
Next fruit

你也可以加点逻辑判断,比如找负数:

For Each num In myArray
  If num < 0>

要提前结束循环就用Exit For,跳过某次迭代用Continue For,比如:

For Each item In myList
  If item = "Banana" Then
    Exit For
  ElseIf item = "Cherry" Then
    Continue For
  End If
  Console.WriteLine(item)
Next item

还有一个挺实用的场景是遍历自定义类型,比如一堆Person对象:

Public Class Person
  Public Property Name As String
  Public Property Age As Integer
End Class

Dim people As New List(Of Person) From { New Person With {.Name = "Tom", .Age = 25}, New Person With {.Name = "Jerry", .Age = 30} }

For Each person In people Console.WriteLine($"姓名:{person.Name},年龄:{person.Age}") Next person

写 VB 项目的时候,不想被复杂的循环搞烦,可以多用For Each。尤其你要一些集合类的数据时,配合IEnumerable的对象,用起来还挺香的。如果你还不熟,建议试试,会少踩不少坑。

rar 文件大小:36.13KB