Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 20 ENUMERATORS AND ITERATORS

Using an Iterator to Create an Enumerable

The previous example created a class comprising two parts: the iterator that produced the enumerator and the GetEnumerator method that returned that enumerator. In this example, the iterator is used to create an enumerable rather than an enumerator. There are some important differences between this example and the last:

In the previous example, iterator method BlackAndWhite returned an IEnumerator<string>, and MyClass implemented method GetEnumerator by returning the object created by BlackAndWhite.

In this example, the iterator method BlackAndWhite returns an IEnumerable<string> rather than an IEnumerator<string>. MyClass, therefore, implements its GetEnumerator method by first calling method BlackAndWhite to get the enumerable object and then calling that object’s GetEnumerator method and returning its results.

Notice that in the foreach statement in Main, you can either use an instance of the class or call BlackAndWhite directly, since it returns an enumerable. Both ways are shown.

class MyClass

{

public IEnumerator<string> GetEnumerator()

{

 

IEnumerable<string> myEnumerable = BlackAndWhite();

//

Get

enumerable

 

return myEnumerable.GetEnumerator();

//

Get

enumerator

}

Returns an enumerable

 

 

 

public IEnumerable<string> BlackAndWhite()

{

yield return "black"; yield return "gray"; yield return "white";

}

}

class Program

{

static void Main()

{

MyClass mc = new MyClass();

Use the class object.

foreach (string shade in mc)

Console.Write("{0} ", shade);

Use the class iterator method.

foreach (string shade in mc.BlackAndWhite()) Console.Write("{0} ", shade);

}

}

528

CHAPTER 20 ENUMERATORS AND ITERATORS

This code produces the following output:

black gray white black gray white

Figure 20-10 illustrates the generic enumerable produced by the enumerable iterator in the code.

The iterator’s code is shown on the left side of the figure and shows that its return type is

IEnumerable<string>.

On the right side of the figure, the diagram shows that the nested class implements both

IEnumerator<string> and IEnumerable<string>.

Figure 20-10. The compiler produces a class that is both an enumerable and an enumerator. It also

produces the method, BlackAndWhite, that returns the Enumerable object.

529

p

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]