次の方法で共有


反復子 (Visual Basic)

関数または Get アクセサーが反復子であることを指定します。

注釈

反復子は、コレクションに対してカスタムイテレーションを実行します。 反復子は Yield ステートメントを使用して、コレクション内の各要素を一度に 1 つずつ返します。 Yieldステートメントに達すると、コード内の現在の場所が保持されます。 反復子関数が次回呼び出されるときに、その場所から実行が再開されます。

反復子は、関数として、またはプロパティ定義の Get アクセサーとして実装できます。 Iterator修飾子は、反復子関数または Get アクセサーの宣言に表示されます。

For Each... を使用して、クライアント コードから反復子を呼び出 します。次のステートメント

反復子関数または Get アクセサーの戻り値の型は、 IEnumerableIEnumerable<T>IEnumerator、または IEnumerator<T>できます。

反復子に ByRef パラメーターを指定することはできません。

反復子は、イベント、インスタンス コンストラクター、静的コンストラクター、または静的デストラクターでは発生できません。

反復子には匿名関数を指定できます。 詳細については、「 反復子」を参照してください。

使用方法

Iterator修飾子は、次のコンテキストで使用できます。

例 1

反復子関数の例を次に示します。 反復子関数には、For... 内にYieldステートメントがあります。次のループ。 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

その他の例については、「 反復子」を参照してください。

こちらも参照ください