# Iterator (Visual Basic)Iterator (Visual Basic)

## 備註Remarks

Iterator 函數或 Get 存取子的傳回類型可以是 IEnumerableIEnumerable<T>IEnumeratorIEnumerator<T>The return type of an iterator function or Get accessor can be IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>.

Iterator 可以是匿名函式。An iterator can be an anonymous function. 如需詳細資訊，請參閱迭代器For more information, see Iterators.

## 使用方式Usage

Iterator 修飾詞可用於以下內容：The Iterator modifier can be used in these contexts:

## 範例Example

Sub Main()
For Each number In Power(2, 8)
Console.Write(number & " ")
Next
' Output: 2 4 8 16 32 64 128 256
End Sub

Private Iterator Function Power(
ByVal base As Integer, ByVal highExponent As Integer) _
As System.Collections.Generic.IEnumerable(Of Integer)

Dim result = 1

For counter = 1 To highExponent
result = result * base
Yield result
Next
End Function


## 範例Example

Sub Main()
Dim theGalaxies As New Galaxies
For Each theGalaxy In theGalaxies.NextGalaxy
With theGalaxy
Console.WriteLine(.Name & "  " & .MegaLightYears)
End With
Next
End Sub

Public Class Galaxies
Public ReadOnly Iterator Property NextGalaxy _
As System.Collections.Generic.IEnumerable(Of Galaxy)
Get
Yield New Galaxy With {.Name = "Tadpole", .MegaLightYears = 400}
Yield New Galaxy With {.Name = "Pinwheel", .MegaLightYears = 25}
Yield New Galaxy With {.Name = "Milky Way", .MegaLightYears = 0}
Yield New Galaxy With {.Name = "Andromeda", .MegaLightYears = 3}
End Get
End Property
End Class

Public Class Galaxy
Public Property Name As String
Public Property MegaLightYears As Integer
End Class