反復子(イテレーター)とは?
反復子を言葉で説明するは難しいので、例を見たほうが理解しやすいでしょう。
Imports System.Collections.Generic Sub Main() For Each number In Power(2, 8) Console.Write(number & " ") Next Console.ReadKey() End Sub Private Iterator Function Power( ByVal base As Integer, _ ByVal highExponent As Integer) _ As IEnumerable(Of Integer) Dim result = 1 For counter = 1 To highExponent result = result * base Yield result Next End Function
解説
Power()はユーザー定義の関数です。「Function」の前に「Iterator」キーワードが付いていることに注目してください。「Iterator」が反復子を表すキーワードです。
Power()の返値の型はIEnumerable(Of T)となっています。これは、For Each で列挙できるコレクションを返却することを意味します。
次に、「Yield」に注目してください。「Iterator」は「Yield」を伴い、要素を順番に列挙していきます。
結果は以下のようになります。
2 4 8 16 32 64 128 256
もう一例、今度はプロパティのイテレーターの例です。
Imports System.Collections.Generic 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 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
解説
Galaxiesはユーザー定義のクラスです。その中の「NextGalaxy」プロパティにおいて、「Property」の前に「Iterator」キーワードが付いていることに注目してください。「Iterator」が反復子を表すキーワードです。
「NextGalaxy」の返値の型はIEnumerable(Of T)となっています。これは、For Each で列挙できるコレクションを返却することを意味します。
次に、「Yield」に注目してください。「Iterator」は「Yield」を伴い、要素を順番に列挙していきます。
ここでは、ユーザー定義の「Galaxy」クラスのインスタンスを順番に4つ返却しています。
なお、ここでは、オブジェクト初期化子を使って、インスタンス化と同時に初期値をセットしています。
結果は以下のようになります。
Tadpole 400 Pinwheel 25 Milky Way 0 Andromeda 3
参考