Iteratory (Visual Basic)Iterators (Visual Basic)
Iterator może służyć do przechodzenia między kolekcjami, takimi jak listy i tablice.An iterator can be used to step through collections such as lists and arrays.
Metoda iteratora lub get
akcesor wykonuje niestandardową iterację w kolekcji.An iterator method or get
accessor performs a custom iteration over a collection. Metoda iterator używa instrukcji Yield do zwrócenia każdego elementu w czasie.An iterator method uses the Yield statement to return each element one at a time. Po Yield
osiągnięciu instrukcji zostanie zapamiętana bieżąca lokalizacja w kodzie.When a Yield
statement is reached, the current location in code is remembered. Wykonanie jest uruchamiane ponownie z tej lokalizacji przy następnym wywołaniu funkcji iteratora.Execution is restarted from that location the next time the iterator function is called.
Iterator z kodu klienta jest używany przez ... Następna instrukcja lub przy użyciu zapytania LINQ.You consume an iterator from client code by using a For Each…Next statement, or by using a LINQ query.
W poniższym przykładzie pierwsza iteracja pętli powoduje, że For Each
wykonywanie jest wykonywane w SomeNumbers
metodzie iteratora do momentu Yield
osiągnięcia pierwszej instrukcji.In the following example, the first iteration of the For Each
loop causes execution to proceed in the SomeNumbers
iterator method until the first Yield
statement is reached. Ta iteracja zwraca wartość 3, a bieżąca lokalizacja w metodzie iteratora jest zachowywana.This iteration returns a value of 3, and the current location in the iterator method is retained. W następnej iteracji pętli wykonywanie w metodzie iteratora jest kontynuowane od miejsca, w którym została pozostawiona, po osiągnięciu Yield
instrukcji.On the next iteration of the loop, execution in the iterator method continues from where it left off, again stopping when it reaches a Yield
statement. Ta iteracja zwraca wartość 5, a bieżąca lokalizacja w metodzie iteratora jest zachowywana ponownie.This iteration returns a value of 5, and the current location in the iterator method is again retained. Pętla kończy się, gdy zostanie osiągnięty koniec metody iteratora.The loop completes when the end of the iterator method is reached.
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
Typem zwracanym metody iteratora lub get
akcesora może być IEnumerable , IEnumerable<T> , IEnumerator , lub IEnumerator<T> .The return type of an iterator method or get
accessor can be IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>.
Możesz użyć Exit Function
instrukcji lub, Return
Aby zakończyć iterację.You can use an Exit Function
or Return
statement to end the iteration.
Funkcja iteratora Visual Basic lub get
Deklaracja metody dostępu zawiera modyfikator iteratora .A Visual Basic iterator function or get
accessor declaration includes an Iterator modifier.
Iteratory zostały wprowadzone w Visual Basic w programie Visual Studio 2012.Iterators were introduced in Visual Basic in Visual Studio 2012.
W tym temacieIn this topic
Uwaga
Wszystkie przykłady w temacie z wyjątkiem prostego przykładu iteratora zawierają instrukcje Importy dla System.Collections
i System.Collections.Generic
przestrzeni nazw.For all examples in the topic except the Simple Iterator example, include Imports statements for the System.Collections
and System.Collections.Generic
namespaces.
Iterator prostySimple Iterator
Poniższy przykład zawiera pojedynczą Yield
instrukcję, która znajduje się wewnątrz elementu ... Następna pętla.The following example has a single Yield
statement that is inside a For…Next loop. W programie Main
każda iteracja For Each
treści instrukcji tworzy wywołanie funkcji iteratora, która przechodzi do następnej Yield
instrukcji.In Main
, each iteration of the For Each
statement body creates a call to the iterator function, which proceeds to the next Yield
statement.
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
Tworzenie klasy kolekcjiCreating a Collection Class
W poniższym przykładzie DaysOfTheWeek
Klasa implementuje IEnumerable interfejs, który wymaga GetEnumerator metody.In the following example, the DaysOfTheWeek
class implements the IEnumerable interface, which requires a GetEnumerator method. Kompilator niejawnie wywołuje GetEnumerator
metodę, która zwraca IEnumerator .The compiler implicitly calls the GetEnumerator
method, which returns an IEnumerator.
GetEnumerator
Metoda zwraca każdy ciąg pojedynczo przy użyciu Yield
instrukcji, a Iterator
modyfikator jest w deklaracji funkcji.The GetEnumerator
method returns each string one at a time by using the Yield
statement, and an Iterator
modifier is in the function declaration.
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
Poniższy przykład tworzy Zoo
klasę, która zawiera kolekcję zwierząt.The following example creates a Zoo
class that contains a collection of animals.
For Each
Instrukcja odwołująca się do wystąpienia klasy ( theZoo
) niejawnie wywołuje GetEnumerator
metodę.The For Each
statement that refers to the class instance (theZoo
) implicitly calls the GetEnumerator
method. For Each
Instrukcje odwołujące się do Birds
Mammals
właściwości i używają AnimalsForType
nazwanego metody iteratora.The For Each
statements that refer to the Birds
and Mammals
properties use the AnimalsForType
named iterator method.
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
Bloki tryTry Blocks
Visual Basic zezwala Yield
instrukcji w Try
bloku try... Catch... Finally — instrukcja.Visual Basic allows a Yield
statement in the Try
block of a Try...Catch...Finally Statement. Try
Blok, który ma Yield
instrukcję, może mieć Catch
bloki i może mieć Finally
blok.A Try
block that has a Yield
statement can have Catch
blocks, and can have a Finally
block.
Poniższy przykład zawiera Try
bloki, Catch
, i Finally
w funkcji iteratora.The following example includes Try
, Catch
, and Finally
blocks in an iterator function. Finally
Blok w funkcji iterator jest wykonywany przed For Each
ukończeniem iteracji.The Finally
block in the iterator function executes before the For Each
iteration finishes.
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
Instrukcja nie może znajdować się wewnątrz Catch
bloku lub Finally
bloku.A Yield
statement cannot be inside a Catch
block or a Finally
block.
Jeśli For Each
treść (zamiast metody iteratora) zgłasza wyjątek, Catch
blok w funkcji iteratora nie zostanie wykonany, ale Finally
jest wykonywany blok w funkcji iteratora.If the For Each
body (instead of the iterator method) throws an exception, a Catch
block in the iterator function is not executed, but a Finally
block in the iterator function is executed. Catch
Blok wewnątrz funkcji iteratora przechwytuje tylko wyjątki, które występują wewnątrz funkcji iteratora.A Catch
block inside an iterator function catches only exceptions that occur inside the iterator function.
Metody anonimoweAnonymous Methods
W Visual Basic funkcja anonimowa może być funkcją iteratora.In Visual Basic, an anonymous function can be an iterator function. Ilustruje to poniższy przykład.The following example illustrates this.
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()
Poniższy przykład ma metodę nieiteracyjną, która weryfikuje argumenty.The following example has a non-iterator method that validates the arguments. Metoda zwraca wynik iteratora anonimowego, który opisuje elementy kolekcji.The method returns the result of an anonymous iterator that describes the collection elements.
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
Jeśli walidacja jest w funkcji iteratora, walidacja nie może zostać wykonana do momentu rozpoczęcia pierwszej iteracji For Each
treści.If validation is instead inside the iterator function, the validation cannot be performed until the start of the first iteration of the For Each
body.
Używanie iteratorów z listą ogólnąUsing Iterators with a Generic List
W poniższym przykładzie Stack(Of T)
Klasa generyczna implementuje IEnumerable<T> interfejs generyczny.In the following example, the Stack(Of T)
generic class implements the IEnumerable<T> generic interface. Push
Metoda przypisuje wartości do tablicy typu T
.The Push
method assigns values to an array of type T
. GetEnumeratorMetoda zwraca wartości tablicy przy użyciu Yield
instrukcji.The GetEnumerator method returns the array values by using the Yield
statement.
Oprócz GetEnumerator metody ogólnej GetEnumerator należy również zaimplementować metodę nierodzajową.In addition to the generic GetEnumerator method, the non-generic GetEnumerator method must also be implemented. Wynika to z faktu, że IEnumerable<T> dziedziczy z IEnumerable .This is because IEnumerable<T> inherits from IEnumerable. Implementacja nieogólna odłożenia do ogólnej implementacji.The non-generic implementation defers to the generic implementation.
W przykładzie używa się nazwanych iteratorów do obsługi różnych sposobów iterowania za pośrednictwem tej samej kolekcji danych.The example uses named iterators to support various ways of iterating through the same collection of data. Te nazwane Iteratory to TopToBottom
właściwości i i BottomToTop
TopN
Metoda.These named iterators are the TopToBottom
and BottomToTop
properties, and the TopN
method.
BottomToTop
Deklaracja właściwości zawiera Iterator
słowo kluczowe.The BottomToTop
property declaration includes the Iterator
keyword.
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
Informacje o składniSyntax Information
Iterator może wystąpić jako metoda lub get
akcesor.An iterator can occur as a method or get
accessor. Iterator nie może wystąpić w zdarzeniu, konstruktorze wystąpień, konstruktorze statycznym lub destruktorze statycznym.An iterator cannot occur in an event, instance constructor, static constructor, or static destructor.
Niejawna konwersja musi istnieć z typu wyrażenia w Yield
instrukcji do zwracanego typu iteratora.An implicit conversion must exist from the expression type in the Yield
statement to the return type of the iterator.
W Visual Basic Metoda iteratora nie może mieć żadnych ByRef
parametrów.In Visual Basic, an iterator method cannot have any ByRef
parameters.
W Visual Basic "Yield" nie jest słowem zastrzeżonym i ma specjalne znaczenie tylko wtedy, gdy jest używany w Iterator
metodzie lub get
akcesorze.In Visual Basic, "Yield" is not a reserved word and has special meaning only when it is used in an Iterator
method or get
accessor.
Implementacja technicznaTechnical Implementation
Chociaż należy napisać iterator jako metodę, kompilator tłumaczy go na zagnieżdżoną klasę, która jest, w efekcie, komputera stanu.Although you write an iterator as a method, the compiler translates it into a nested class that is, in effect, a state machine. Ta klasa śledzi pozycję iteratora, tak długo For Each...Next
Pętla w kodzie klienta jest kontynuowana.This class keeps track of the position of the iterator as long the For Each...Next
loop in the client code continues.
Aby zobaczyć, co robi kompilator, możesz użyć narzędzia Ildasm.exe, aby wyświetlić kod języka pośredniego firmy Microsoft, który jest generowany dla metody iterator.To see what the compiler does, you can use the Ildasm.exe tool to view the Microsoft intermediate language code that is generated for an iterator method.
Podczas tworzenia iteratora dla klasy lub strukturynie trzeba implementować całego IEnumerator interfejsu.When you create an iterator for a class or struct, you do not have to implement the whole IEnumerator interface. Gdy kompilator wykryje iterator, automatycznie generuje Current
MoveNext
metody,, i Dispose
IEnumerator IEnumerator<T> interfejsu.When the compiler detects the iterator, it automatically generates the Current
, MoveNext
, and Dispose
methods of the IEnumerator or IEnumerator<T> interface.
Dla każdej kolejnej iteracji For Each…Next
pętli (lub bezpośredniego wywołania do IEnumerator.MoveNext
) Następna treść kodu iteratora zostanie wznowiona po poprzedniej Yield
instrukcji.On each successive iteration of the For Each…Next
loop (or the direct call to IEnumerator.MoveNext
), the next iterator code body resumes after the previous Yield
statement. Następnie przechodzi do następnej Yield
instrukcji do momentu osiągnięcia końca treści iteratora lub do momentu Exit Function
Return
napotkania instrukcji lub.It then continues to the next Yield
statement until the end of the iterator body is reached, or until an Exit Function
or Return
statement is encountered.
Iteratory nie obsługują IEnumerator.Reset metody.Iterators do not support the IEnumerator.Reset method. Aby ponownie wykonać iterację od początku, należy uzyskać nowy iterator.To re-iterate from the start, you must obtain a new iterator.
Aby uzyskać dodatkowe informacje, zobacz Specyfikacja języka Visual Basic.For additional information, see the Visual Basic Language Specification.
Użycie iteratorówUse of Iterators
Iteratory umożliwiają zachowanie prostoty For Each
pętli, gdy trzeba użyć kodu złożonego, aby wypełnić sekwencję listy.Iterators enable you to maintain the simplicity of a For Each
loop when you need to use complex code to populate a list sequence. Może to być przydatne, gdy chcesz wykonać następujące czynności:This can be useful when you want to do the following:
Zmodyfikuj sekwencję list po pierwszej
For Each
iteracji pętli.Modify the list sequence after the firstFor Each
loop iteration.Unikaj całkowitego ładowania dużej listy przed pierwszą iteracją
For Each
pętli.Avoid fully loading a large list before the first iteration of aFor Each
loop. Przykładem jest pobieranie stronicowane w celu załadowania partii wierszy tabeli.An example is a paged fetch to load a batch of table rows. Innym przykładem jest EnumerateFiles Metoda, która implementuje Iteratory w .NET Framework.Another example is the EnumerateFiles method, which implements iterators within the .NET Framework.Hermetyzuje Kompilowanie listy w iterator.Encapsulate building the list in the iterator. W metodzie iteratora można skompilować listę, a następnie dać każdy wynik w pętli.In the iterator method, you can build the list and then yield each result in a loop.