指定函式或 Get 存取子是反覆運算器。
備註
反覆運算器會在集合上執行自定義反覆專案。 反覆運算器會使用 Yield 語句一次傳回集合中的每個專案。
Yield到達 語句時,會保留程序代碼中的目前位置。 下次呼叫反覆運算器函式時,會從該位置重新啟動執行。
反覆運算器可以實作為函式或 Get 屬性定義的存取子。
Iterator修飾詞會出現在反覆運算器函式或Get存取子的宣告中。
您可以使用 For Each... 從用戶端程式代碼呼叫反覆運算器 ...Next 語句。
反覆運算器函式或 Get 存取子的傳回型別可以是 IEnumerable、 IEnumerable<T>、 IEnumerator或 IEnumerator<T>。
反覆運算器不能有任何 ByRef 參數。
反覆運算器無法在事件、實例建構函式、靜態建構函式或靜態解構函式中發生。
反覆運算器可以是匿名函式。 如需詳細資訊,請參閱 Iterator。
用法
Iterator修飾詞可用於下列內容:
範例 1
下列範例示範反覆運算器函式。 Iterator 函式有位於 YieldFor... 內的 語句下一個 迴圈。 中 MainFor Each 語句主體的每個反覆運算都會建立反覆運算器函式的Power呼叫。 反覆運算器函式的每個呼叫都會繼續進行語句的下一個執行 Yield ,這會在迴圈的下一個反覆運算 For…Next 期間發生。
Sub Main()
For Each number In Power(2, 8)
Console.Write(number & " ")
Next
' Output: 2 4 8 16 32 64 128 256
Console.ReadKey()
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
範例 2
下列範例示範 Get 反覆運算器的存取子。 修飾 Iterator 詞位於屬性宣告中。
Sub Main()
Dim theGalaxies As New Galaxies
For Each theGalaxy In theGalaxies.NextGalaxy
With theGalaxy
Console.WriteLine(.Name & " " & .MegaLightYears)
End With
Next
Console.ReadKey()
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
如需其他範例,請參閱 反覆運算器。