Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C-sharp language specification.2004.pdf
Скачиваний:
14
Добавлен:
23.08.2013
Размер:
2.55 Mб
Скачать

Chapter 27 Iterators

127. Iterators

2An iterator is a means of implementing a function member whose return type is an enumerator interface or

3enumerable interface. The function member returns the ordered sequence of values as yielded by the iterator.

4[Example: The following Stack<T> class implements its GetEnumerator method using an iterator. The

5iterator enumerates the elements of the stack in top to bottom order.

6using System.Collections.Generic;

7public class Stack<T>: IEnumerable<T>

8{

9

T[] items;

10

int count;

11

public void Push(T data) {…}

12

public T Pop() {…}

13

public IEnumerator<T> GetEnumerator() {

14

for (int i = count – 1; i >= 0; --i) {

15

yield return items[i];

16

}

17}

18}

19The type IEnumerator<T> is an enumerator interface which allows the GetEnumerator method to be

20implemented using an iterator. The presence of the GetEnumerator method makes Stack<T> an

21enumerable type, allowing instances of Stack<T> to be used in a foreach statement. The following

22example pushes the values 0 through 9 onto an integer stack and then uses a foreach loop to display the

23values in top to bottom order.

24using System;

25class Test

26{

27

static void Main() {

28

Stack<int> s = new Stack<int>();

29

for (int i = 0; i < 10; i++) s.Push(i);

30

foreach (int i in s) Console.Write("{0} ", i);

31

Console.WriteLine();

32}

33}

34The output of the example is:

359 8 7 6 5 4 3 2 1 0

36end example]

3727.1 Iterator blocks

38An iterator block is a block (§15.2) that yields an ordered sequence of values. An iterator block is

39distinguished from a normal statement block by the presence of one or more yield statements (§15.14).

40The yield return statement produces the next value of the iteration.

41The yield break statement indicates that the iteration is complete.

42An iterator block can be used as a method-body (§17.5), operator-body (§17.9), or accessor-body (§17.6.2)

43as long as the return type of the corresponding function member is one of the enumerator interfaces

44(§27.1.1) or one of the enumerable interfaces (§27.1.2).

423

Соседние файлы в предмете Электротехника