反復子 (C# および Visual Basic)

リストや配列などのコレクションを実行するために 反復子を 使用できます。

get の反復子のメソッドやアクセサーはコレクションに対するカスタムのイテレーションを実行します。反復子のメソッドは、各要素を一つずつ返すために [Yield] (Visual Basic) または yield を返します。 (C#) ステートメントを使用します。Yield または yield return ステートメントに到達すると、コードの現在の位置が保持されます。実装はその位置から反復子関数が呼び出されるときに再起動されます。

各には、次に… (Visual Basic) または (foreach、C) ステートメントを使用するか、LINQ クエリを使用してクライアント コードからの反復子を実装します。

次の例では、For Each または foreach のループの最初のイテレーションに実行が最初の Yield までの SomeNumbers の反復子のメソッドに移動または yield return ステートメントに到達されます。このイテレーションは値 3 を返し、反復子メソッドの現在の位置は保持されます。ループの次の反復処理で、反復子のメソッドの実装は Yield または yield return ステートメントに到達すると、もう一度停止する場所とプロセスが続行され。このイテレーションは値 5 を返し、反復子メソッドの現在の位置が再び保持されます。ループが反復子のメソッドの最後に到達すると完了します。

Sub Main()
    For Each number As Integer In SomeNumbers()
        Console.Write(number & " ")
    Next
    ' Output: 3 5 8
    Console.ReadKey()
End Sub

Private Iterator Function SomeNumbers() As System.Collections.IEnumerable
    Yield 3
    Yield 5
    Yield 8
End Function
static void Main()
{
    foreach (int number in SomeNumbers())
    {
        Console.Write(number.ToString() + " ");
    }
    // Output: 3 5 8
    Console.ReadKey();
}

public static System.Collections.IEnumerable SomeNumbers()
{
    yield return 3;
    yield return 5;
    yield return 8;
}

get の反復子のメソッドやアクセサーの戻り値の型は IEnumerableIEnumerable<T>IEnumerator、または IEnumerator<T>のいずれかになります。

Exit Function または Return のステートメント (Visual Basic) またはイテレーションの末尾に yield break ステートメント (C#) を使用します。

Visual Basic の反復子関数または get アクセサー申告は [反復子] 修飾子が含まれます。

反復子は Visual Studio 2005C によるで導入され、Visual Studio 2012の Visual Basic で導入されました。

このトピックの内容

  • 単純な反復子

  • コレクション クラスの作成

  • Visual Basic の試行の禁止

  • Visual Basic の匿名メソッド

  • ジェネリック リストの反復子を使用する

  • 構文の詳細

  • 技術的な実装

  • 反復子の使用

単純な反復子

次の例に 次に、… (Visual Basic) または (には、C) のループ内にある yield return の単一の Yield またはステートメントがあります。Mainでは、For Each ステートメントまたは foreach のメイン フレームの各反復で yield return の次のステートメントに進む Yield または反復子の関数への呼び出しを作成します。

Sub Main()
    For Each number As Integer In EvenSequence(5, 18)
        Console.Write(number & " ")
    Next
    ' Output: 6 8 10 12 14 16 18
    Console.ReadKey()
End Sub

Private Iterator Function EvenSequence(
ByVal firstNumber As Integer, ByVal lastNumber As Integer) _
As System.Collections.Generic.IEnumerable(Of Integer)

    ' Yield even numbers in the range.
    For number As Integer = firstNumber To lastNumber
        If number Mod 2 = 0 Then
            Yield number
        End If
    Next
End Function
static void Main()
{
    foreach (int number in EvenSequence(5, 18))
    {
        Console.Write(number.ToString() + " ");
    }
    // Output: 6 8 10 12 14 16 18
    Console.ReadKey();
}

public static System.Collections.Generic.IEnumerable<int>
    EvenSequence(int firstNumber, int lastNumber)
{
    // Yield even numbers in the range.
    for (int number = firstNumber; number <= lastNumber; number++)
    {
        if (number % 2 == 0)
        {
            yield return number;
        }
    }
}

コレクション クラスの作成

[!メモ]

トピックの残りの例については、[インポート] のステートメント (Visual Basic) または System.Collections.GenericSystem.Collections と名前空間に対するディレクティブ ([using]、C) します。

次の例では、DaysOfTheWeek のクラスは GetEnumerator のメソッドを必要とする IEnumerable のインターフェイスを実装します。コンパイラは、暗黙的に IEnumeratorを返す GetEnumerator のメソッドを呼び出します。

GetEnumerator のメソッドは Yield または yield return ステートメントを使用して各文字列を一つずつ返します。Visual Basic コードでは、Iterator の修飾子は、関数の宣言にあります。

Sub Main()
    Dim days As New DaysOfTheWeek()
    For Each day As String In days
        Console.Write(day & " ")
    Next
    ' Output: Sun Mon Tue Wed Thu Fri Sat
    Console.ReadKey()
End Sub

Private Class DaysOfTheWeek
    Implements IEnumerable

    Public days =
        New String() {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}

    Public Iterator Function GetEnumerator() As IEnumerator _
        Implements IEnumerable.GetEnumerator

        ' Yield each day of the week.
        For i As Integer = 0 To days.Length - 1
            Yield days(i)
        Next
    End Function
End Class
static void Main()
{
    DaysOfTheWeek days = new DaysOfTheWeek();

    foreach (string day in days)
    {
        Console.Write(day + " ");
    }
    // Output: Sun Mon Tue Wed Thu Fri Sat
    Console.ReadKey();
}

public class DaysOfTheWeek : IEnumerable
{
    private string[] days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

    public IEnumerator GetEnumerator()
    {
        for (int index = 0; index < days.Length; index++)
        {
            // Yield each day of the week.
            yield return days[index];
        }
    }
}

次の例では動物のコレクションを含む Zoo のクラスを作成します。

クラスのインスタンス (theZoo) を暗黙的に示す For Each または foreach のステートメントは GetEnumerator のメソッドを呼び出します。Birds と Mammals のプロパティを表示 For Each または foreach のステートメントは、反復子のメソッドという名前の AnimalsForType を使用します。

Sub Main()
    Dim theZoo As New Zoo()

    theZoo.AddMammal("Whale")
    theZoo.AddMammal("Rhinoceros")
    theZoo.AddBird("Penguin")
    theZoo.AddBird("Warbler")

    For Each name As String In theZoo
        Console.Write(name & " ")
    Next
    Console.WriteLine()
    ' Output: Whale Rhinoceros Penguin Warbler

    For Each name As String In theZoo.Birds
        Console.Write(name & " ")
    Next
    Console.WriteLine()
    ' Output: Penguin Warbler

    For Each name As String In theZoo.Mammals
        Console.Write(name & " ")
    Next
    Console.WriteLine()
    ' Output: Whale Rhinoceros

    Console.ReadKey()
End Sub

Public Class Zoo
    Implements IEnumerable

    ' Private members.
    Private animals As New List(Of Animal)

    ' Public methods.
    Public Sub AddMammal(ByVal name As String)
        animals.Add(New Animal With {.Name = name, .Type = Animal.TypeEnum.Mammal})
    End Sub

    Public Sub AddBird(ByVal name As String)
        animals.Add(New Animal With {.Name = name, .Type = Animal.TypeEnum.Bird})
    End Sub

    Public Iterator Function GetEnumerator() As IEnumerator _
        Implements IEnumerable.GetEnumerator

        For Each theAnimal As Animal In animals
            Yield theAnimal.Name
        Next
    End Function

    ' Public members.
    Public ReadOnly Property Mammals As IEnumerable
        Get
            Return AnimalsForType(Animal.TypeEnum.Mammal)
        End Get
    End Property

    Public ReadOnly Property Birds As IEnumerable
        Get
            Return AnimalsForType(Animal.TypeEnum.Bird)
        End Get
    End Property

    ' Private methods.
    Private Iterator Function AnimalsForType( _
    ByVal type As Animal.TypeEnum) As IEnumerable
        For Each theAnimal As Animal In animals
            If (theAnimal.Type = type) Then
                Yield theAnimal.Name
            End If
        Next
    End Function

    ' Private class.
    Private Class Animal
        Public Enum TypeEnum
            Bird
            Mammal
        End Enum

        Public Property Name As String
        Public Property Type As TypeEnum
    End Class
End Class
static void Main()
{
    Zoo theZoo = new Zoo();

    theZoo.AddMammal("Whale");
    theZoo.AddMammal("Rhinoceros");
    theZoo.AddBird("Penguin");
    theZoo.AddBird("Warbler");

    foreach (string name in theZoo)
    {
        Console.Write(name + " ");
    }
    Console.WriteLine();
    // Output: Whale Rhinoceros Penguin Warbler

    foreach (string name in theZoo.Birds)
    {
        Console.Write(name + " ");
    }
    Console.WriteLine();
    // Output: Penguin Warbler

    foreach (string name in theZoo.Mammals)
    {
        Console.Write(name + " ");
    }
    Console.WriteLine();
    // Output: Whale Rhinoceros

    Console.ReadKey();
}

public class Zoo : IEnumerable
{
    // Private members.
    private List<Animal> animals = new List<Animal>();

    // Public methods.
    public void AddMammal(string name)
    {
        animals.Add(new Animal { Name = name, Type = Animal.TypeEnum.Mammal });
    }

    public void AddBird(string name)
    {
        animals.Add(new Animal { Name = name, Type = Animal.TypeEnum.Bird });
    }

    public IEnumerator GetEnumerator()
    {
        foreach (Animal theAnimal in animals)
        {
            yield return theAnimal.Name;
        }
    }

    // Public members.
    public IEnumerable Mammals
    {
        get { return AnimalsForType(Animal.TypeEnum.Mammal); }
    }

    public IEnumerable Birds
    {
        get { return AnimalsForType(Animal.TypeEnum.Bird); }
    }

    // Private methods.
    private IEnumerable AnimalsForType(Animal.TypeEnum type)
    {
        foreach (Animal theAnimal in animals)
        {
            if (theAnimal.Type == type)
            {
                yield return theAnimal.Name;
            }
        }
    }

    // Private class.
    private class Animal
    {
        public enum TypeEnum { Bird, Mammal }

        public string Name { get; set; }
        public TypeEnum Type { get; set; }
    }
}

Visual Basic の試行の禁止

Visual Basic は Try...Catch...Finally ステートメント (Visual Basic)の Try ブロックの Yield のステートメントができます。Yield のステートメントがある Try ブロックは Catch ブロックを持ち Finally のブロックを指定できます。

C# メモ : C# メモ

は、C [try-finally] のステートメントの try ブロックの yield return ステートメントができます。yield return ステートメントがある try ブロックは catch ブロックを含めることはできません。

Visual Basic の次の例では Try、Catchが含まれ、反復子の Finally ブロックは機能します。反復子関数のブロック Finally は For Each のイテレーションが終了する前に実行されます。

Sub Main()
    For Each number As Integer In Test()
        Console.WriteLine(number)
    Next
    Console.WriteLine("For Each is done.")

    ' Output:
    '  3
    '  4
    '  Something happened. Yields are done.
    '  Finally is called.
    '  For Each is done.
    Console.ReadKey()
End Sub

Private Iterator Function Test() As IEnumerable(Of Integer)
    Try
        Yield 3
        Yield 4
        Throw New Exception("Something happened. Yields are done.")
        Yield 5
        Yield 6
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    Finally
        Console.WriteLine("Finally is called.")
    End Try
End Function

Yield のステートメントは CatchFinally ブロックまたはブロック内に置くことはできません。

For Each の本体が (反復子のメソッドの代わりに、例外をスローした場合、反復子関数の Catch ブロックは実行されませんが、反復子関数の Finally ブロックが実行されます。反復子関数のブロック Catch は、反復子関数内で発生した例外のみをキャッチします。

Visual Basic の匿名メソッド

Visual Basic ではありません (ただし、C)、匿名関数は、反復子関数です。次に例を示します。

Dim iterateSequence = Iterator Function() _
                      As IEnumerable(Of Integer)
                          Yield 1
                          Yield 2
                      End Function

For Each number As Integer In iterateSequence()
    Console.Write(number & " ")
Next
' Output: 1 2
Console.ReadKey()

Visual Basic の次の例に、引数を検証する非反復子のメソッドがあります。メソッドは、コレクションの要素を説明する匿名反復子の結果を返します。

Sub Main()
    For Each number As Integer In GetSequence(5, 10)
        Console.Write(number & " ")
    Next
    ' Output: 5 6 7 8 9 10
    Console.ReadKey()
End Sub

Public Function GetSequence(ByVal low As Integer, ByVal high As Integer) _
As IEnumerable
    ' Validate the arguments.
    If low < 1 Then
        Throw New ArgumentException("low is too low")
    End If
    If high > 140 Then
        Throw New ArgumentException("high is too high")
    End If

    ' Return an anonymous iterator function.
    Dim iterateSequence = Iterator Function() As IEnumerable
                              For index = low To high
                                  Yield index
                              Next
                          End Function
    Return iterateSequence()
End Function

検証が反復子関数内にある場合、検証は For Each 本体の最初のイテレーションの開始まで実行できません。

ジェネリック リストの反復子を使用する

次の例では、Stack(Of T) のジェネリック クラスは IEnumerable<T> のジェネリック インターフェイスも実装します。Push のメソッドは型 Tの値を配列に再配置。GetEnumerator のメソッドは Yield または yield return ステートメントを使用して、配列の値を返します。

GetEnumerator のジェネリック メソッドに加えて、GetEnumerator の非ジェネリック メソッドも実装する必要があります。これは IEnumerable<T>IEnumerableから継承するためです。一般的な実装に非ジェネリックの遅延。

例では、同じデータ コレクションを通じて繰り返すさまざまな方法をサポートするには、名前付き反復子を使用します。これらの名前付き反復子は TopToBottom と BottomToTop のプロパティ、および TopN のメソッドです。

BottomToTop のプロパティは get のアクセサーで反復子を使用します。Visual Basic コードでは、プロパティの申告は Iterator のキーワードが含まれています。

Sub Main()
    Dim theStack As New Stack(Of Integer)

    ' Add items to the stack.
    For number As Integer = 0 To 9
        theStack.Push(number)
    Next

    ' Retrieve items from the stack.
    ' For Each is allowed because theStack implements
    ' IEnumerable(Of Integer).
    For Each number As Integer In theStack
        Console.Write("{0} ", number)
    Next
    Console.WriteLine()
    ' Output: 9 8 7 6 5 4 3 2 1 0

    ' For Each is allowed, because theStack.TopToBottom
    ' returns IEnumerable(Of Integer).
    For Each number As Integer In theStack.TopToBottom
        Console.Write("{0} ", number)
    Next
    Console.WriteLine()
    ' Output: 9 8 7 6 5 4 3 2 1 0

    For Each number As Integer In theStack.BottomToTop
        Console.Write("{0} ", number)
    Next
    Console.WriteLine()
    ' Output: 0 1 2 3 4 5 6 7 8 9 

    For Each number As Integer In theStack.TopN(7)
        Console.Write("{0} ", number)
    Next
    Console.WriteLine()
    ' Output: 9 8 7 6 5 4 3

    Console.ReadKey()
End Sub

Public Class Stack(Of T)
    Implements IEnumerable(Of T)

    Private values As T() = New T(99) {}
    Private top As Integer = 0

    Public Sub Push(ByVal t As T)
        values(top) = t
        top = top + 1
    End Sub

    Public Function Pop() As T
        top = top - 1
        Return values(top)
    End Function

    ' This function implements the GetEnumerator method. It allows
    ' an instance of the class to be used in a For Each statement.
    Public Iterator Function GetEnumerator() As IEnumerator(Of T) _
        Implements IEnumerable(Of T).GetEnumerator

        For index As Integer = top - 1 To 0 Step -1
            Yield values(index)
        Next
    End Function

    Public Iterator Function GetEnumerator1() As IEnumerator _
        Implements IEnumerable.GetEnumerator

        Yield GetEnumerator()
    End Function

    Public ReadOnly Property TopToBottom() As IEnumerable(Of T)
        Get
            Return Me
        End Get
    End Property

    Public ReadOnly Iterator Property BottomToTop As IEnumerable(Of T)
        Get
            For index As Integer = 0 To top - 1
                Yield values(index)
            Next
        End Get
    End Property

    Public Iterator Function TopN(ByVal itemsFromTop As Integer) _
        As IEnumerable(Of T)

        ' Return less than itemsFromTop if necessary.
        Dim startIndex As Integer =
            If(itemsFromTop >= top, 0, top - itemsFromTop)

        For index As Integer = top - 1 To startIndex Step -1
            Yield values(index)
        Next
    End Function
End Class
static void Main()
{
    Stack<int> theStack = new Stack<int>();

    //  Add items to the stack.
    for (int number = 0; number <= 9; number++)
    {
        theStack.Push(number);
    }

    // Retrieve items from the stack.
    // foreach is allowed because theStack implements
    // IEnumerable<int>.
    foreach (int number in theStack)
    {
        Console.Write("{0} ", number);
    }
    Console.WriteLine();
    // Output: 9 8 7 6 5 4 3 2 1 0

    // foreach is allowed, because theStack.TopToBottom
    // returns IEnumerable(Of Integer).
    foreach (int number in theStack.TopToBottom)
    {
        Console.Write("{0} ", number);
    }
    Console.WriteLine();
    // Output: 9 8 7 6 5 4 3 2 1 0

    foreach (int number in theStack.BottomToTop)
    {
        Console.Write("{0} ", number);
    }
    Console.WriteLine();
    // Output: 0 1 2 3 4 5 6 7 8 9

    foreach (int number in theStack.TopN(7))
    {
        Console.Write("{0} ", number);
    }
    Console.WriteLine();
    // Output: 9 8 7 6 5 4 3

    Console.ReadKey();
}

public class Stack<T> : IEnumerable<T>
{
    private T[] values = new T[100];
    private int top = 0;

    public void Push(T t)
    {
        values[top] = t;
        top++;
    }
    public T Pop()
    {
        top--;
        return values[top];
    }

    // This method implements the GetEnumerator method. It allows
    // an instance of the class to be used in a foreach statement.
    public IEnumerator<T> GetEnumerator()
    {
        for (int index = top - 1; index >= 0; index--)
        {
            yield return values[index];
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public IEnumerable<T> TopToBottom
    {
        get { return this; }
    }

    public IEnumerable<T> BottomToTop
    {
        get
        {
            for (int index = 0; index <= top - 1; index++)
            {
                yield return values[index];
            }
        }
    }

    public IEnumerable<T> TopN(int itemsFromTop)
    {
        // Return less than itemsFromTop if necessary.
        int startIndex = itemsFromTop >= top ? 0 : top - itemsFromTop;

        for (int index = top - 1; index >= startIndex; index--)
        {
            yield return values[index];
        }
    }

}

構文の詳細

反復子は get のメソッドやアクセサーとして発生することがあります。反復子は、イベント インスタンス コンストラクター、静的コンストラクター、または静的なデストラクターで発生することはできません。

暗黙の変換は型に Yield (Visual Basic) または yield return (C#) ステートメントの反復子をからの戻り値の型の式ある必要があります。

Visual Basicでは、反復子のメソッドは ByRef のパラメーターを持つことはできません。では、C、反復子のメソッドは ref または out のパラメーターを持つことはできません。

Visual Basicでは、get の Iterator のメソッドやアクセサーで使用されている場合にのみ "yield" に予約語ではなく、特別な意味を持ちます。では、return、C または break のキーワードの前に使用する場合にのみ "yield" に予約語ではなく、特別な意味を持ちます。

技術的な実装

反復子をメソッドとして記述しても、コンパイラが入れ子のクラス、つまり事実上ステート マシンに変換します。このクラスは For Each...Next として反復子の位置を追跡します。または、クライアント コードで foreach のループが継続されます。

コンパイラの動作を確認するには、反復子メソッドに生成する Microsoft Intermediate Language) コードを表示するには、Ildasm.exe のツールを使用できます。

クラス または 構造体の反復子を作成すると、IEnumerator のすべてのインターフェイスを実装する必要はありません。コンパイラが反復子を検出すると、自動的に IEnumerator または IEnumerator<T> のインターフェイス Current、MoveNextと Dispose メソッドが生成されます。

For Each…Next または foreach のループ (または IEnumerator.MoveNextへの直接呼び出し) の後続のイテレーション、yield return の前の Yield またはステートメントの後の次の反復子コード本体が再開します。これは yield return の次の Yield またはステートメントに、反復子本体の最後に到達する、または Exit Function または Return のステートメント (Visual Basic) または yield break (C#) のステートメントまで達するまで続行されます。

反復子は、IEnumerator.Reset メソッドをサポートしません。先頭から再度行う場合は、新しい反復子を取得する必要があります。

追加情報については、Visual Basic 言語仕様 または C# 言語仕様) を参照してください。

反復子の使用

反復子は、リストのシーケンスに対する複雑なコードを使用する必要がある場合 For Each ループの単純化を保持できるようにします。これは、次の操作を行う場合に便利です:

  • リストのシーケンスを後の最初の For Each のループ反復変更されています。

  • 前に For Each ループの最初のイテレーション大きいリストを読み込むことは避けてください。例では、テーブルの行のバッチを読み込むページをページング フェッチです。また、.NET Framework 内の反復子を実装する EnumerateFiles のメソッドです。

  • 反復子のリストを構築カプセル化します。反復子のメソッドでは、リストをビルドし、ループの各結果が生じる可能性があります。

次に、C のブログは、反復子の使用に関する追加情報を提供します。

参照

関連項目

For Each...Next ステートメント (Visual Basic)

foreach、in (C# リファレンス)

Yield ステートメント (Visual Basic)

yield (C# リファレンス)

反復子 (Visual Basic)

配列での foreach の使用 (C# プログラミング ガイド)

ジェネリック (C# プログラミング ガイド)

System.Collections.Generic

IEnumerable<T>