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

CHAPTER 20 ENUMERATORS AND ITERATORS

The IEnumerable<T> Interface

The generic IEnumerable<T> interface is very similar to the nongeneric version, IEnumerable. The generic version derives from IEnumerable, so it must also implement the IEnumerable interface.

Like IEnumerable, the generic version also contains a single member, a method called GetEnumerator. This version of GetEnumerator, however, returns a class object implementing the generic IEnumerator<T> interface.

Since the class must implement two GetEnumerator methods, you should explicitly implement the nongeneric version and implement the generic version at the class level, as shown in Figure 20-7.

Figure 20-7 illustrates the implementation of the interface.

Figure 20-7. Implementing the IEnumerable<T> interface

522

CHAPTER 20 ENUMERATORS AND ITERATORS

The following code shows a pattern for implementing the generic interface. T is the type returned by the enumerator.

using System.Collections;

using System.Collections.Generic;

class MyGenEnumerable: IEnumerable<T>

{

public

IEnumerator<T> GetEnumerator() {

... }

//

IEnumerable<T> version

 

 

Explicit implementation

 

 

 

 

 

 

 

 

 

IEnumerator IEnumerable.GetEnumerator()

{ ... }

//

IEnumerable version

...

 

 

 

 

 

 

}

The following code shows the use of the generic enumerable interface:

using System.Collections;

 

using System.Collections.Generic;

 

 

Substitute actual type for T

 

 

 

class MyColors : IEnumerable<string>

 

{

 

 

 

string[] Colors = { "Red", "Yellow", "Blue" };

 

 

Substitute actual type for T

 

 

 

public IEnumerator<string> GetEnumerator()

// IEnumerable<T> version

{

 

 

 

return new ColorEnumerator(Colors);

 

}

Explicit implementation

 

 

 

 

 

 

IEnumerator IEnumerable.GetEnumerator()

// IEnumerable version

{

 

 

 

return new ColorEnumerator(Colors);

 

}

 

 

 

}

 

 

 

523

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