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

CHAPTER 20 ENUMERATORS AND ITERATORS

The IEnumerable Interface

The IEnumerable interface has only a single member, method GetEnumerator, which returns an enumerator for the object.

Figure 20-4 shows class MyClass, which has three items to enumerate, and implements the IEnumerable interface by implementing the GetEnumerator method.

Figure 20-4. The GetEnumerator method returns an enumerator object for the class.

The following code shows the form for the declaration of an enumerable class:

using System.Collections;

Implements the IEnumerable interface

class MyClass : IEnumerable

{

public IEnumerator GetEnumerator { ... }

...

}Returns an object of type IEnumerator

The following code gives an example of an enumerable class that uses enumerator class ColorEnumerator from the previous example. Remember that ColorEnumerator implements IEnumerator.

using System.Collections;

class MyColors: IEnumerable

{

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

public IEnumerator GetEnumerator()

{

 

return new ColorEnumerator(Colors);

}

 

 

}

 

An instance of the enumerator class

513

CHAPTER 20 ENUMERATORS AND ITERATORS

Example Using IEnumerable and IEnumerator

Putting the MyColors and ColorEnumerator examples together, you can add a class called Program with a Main method that creates an instance of MyColors and uses it in a foreach loop.

using System;

using System.Collections;

namespace ColorCollectionEnumerator

{

class ColorEnumerator: IEnumerator

{

string[] Colors; int Position = -1;

public ColorEnumerator(string[] theColors)

// Constructor

{

 

Colors = new string[theColors.Length];

 

for (int i = 0; i < theColors.Length; i++)

 

Colors[i] = theColors[i];

 

}

 

public object Current

// Current

{

 

get

 

{

 

if (Position == -1)

 

{

 

throw new InvalidOperationException();

 

}

 

if (Position == Colors.Length)

 

{

 

throw new InvalidOperationException();

 

}

 

return Colors[Position];

 

}

 

}

 

public bool MoveNext()

// MoveNext

{

 

if (Position < Colors.Length - 1)

 

{

 

Position++;

 

return true;

 

}

 

else

 

return false;

 

}

 

public void Reset()

// Reset

{ Position = -1; }

 

}

514

CHAPTER 20 ENUMERATORS AND ITERATORS

class MyColors: IEnumerable

{

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

public IEnumerator GetEnumerator()

{

return new ColorEnumerator(Colors);

}

}

class Program

{

static void Main()

{

MyColors mc = new MyColors(); foreach (string color in mc)

Console.WriteLine(color);

}

}

}

This code produces the following output:

Red

Yellow

Blue

515

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