Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
22
Добавлен:
25.03.2016
Размер:
13.96 Mб
Скачать

Chapter 19

Enumerating Collections

After completing this chapter, you will be able to:

Manually define an enumerator that can be used to iterate over the elements in a collection.

Implement an enumerator automatically by creating an iterator.

Provide additional iterators that can step through the elements of a collection in different sequences.

In Chapter 10, “Using Arrays and Collections,” you learned about arrays and collection classes for holding sequences or sets of data. Chapter 10 also introduced the foreach statement that

you can use for stepping through, or iterating over, the elements in a collection. At the time, you just used the foreach statement as a quick and convenient way of accessing the contents

of a collection, but now it is time to learn a little more about how this statement actually works. This topic becomes important when you start defining your own collection classes. Fortunately, C# provides iterators to help you automate much of the process.

Enumerating the Elements in a Collection

In Chapter 10, you saw an example of using the foreach statement to list the items in a simple array. The code looked like this:

int[] pins = { 9, 3, 7, 2 }; foreach (int pin in pins)

{

Console.WriteLine(pin);

}

The foreach construct provides an elegant mechanism that greatly simplifies the code that

you need to write, but it can be exercised only under certain circumstances—you can use foreach only to step through an enumerable collection. So, what exactly is an enumerable collection? The quick answer is that it is a collection that implements the System.Collections. IEnumerable interface.

Note Remember that all arrays in C# are actually instances of the System.Array class. The System.Array class is a collection class that implements the IEnumerable interface.

355

356 Part III Creating Components

The IEnumerable interface contains a single method called GetEnumerator:

IEnumerator GetEnumerator();

The GetEnumerator method should return an enumerator object that implements the System. Collections.IEnumerator interface. The enumerator object is used for stepping through (enumerating) the elements of the collection. The IEnumerator interface specifies the following

property and methods:

object Current { get; } bool MoveNext();

void Reset();

Think of an enumerator as a pointer pointing to elements in a list. Initially, the pointer points before the first element. You call the MoveNext method to move the pointer down to the next (first) item in the list; the MoveNext method should return true if there actually is another item and false if there isn’t. You use the Current property to access the item currently pointed to, and you use the Reset method to return the pointer back to before the first item in the list. By creating an enumerator by using the GetEnumerator method of a collection and repeatedly calling the MoveNext method and retrieving the value of the Current property by

using the enumerator, you can move forward through the elements of a collection one item at a time. This is exactly what the foreach statement does. So if you want to create your own enumerable collection class, you must implement the IEnumerable interface in your collection class and also provide an implementation of the IEnumerator interface to be returned by the GetEnumerator method of the collection class.

Important At first glance, it is easy to confuse the IEnumerable<T> and the IEnumerator<T> interfaces because of the similarity of their names. Don’t get them mixed up.

If you are observant, you will have noticed that the Current property of the IEnumerator interface exhibits non-type-safe behavior in that it returns an object rather than a specific type.

However, you should be pleased to know that the Microsoft .NET Framework class library also provides the generic IEnumerator<T> interface, which has a Current property that returns a T instead. Likewise, there is also an IEnumerable<T> interface containing a GetEnumerator method that returns an Enumerator<T> object. If you are building applications for the .NET

Framework version 2.0 or later, you should make use of these generic interfaces when defining enumerable collections rather than using the nongeneric definitions.

Note The IEnumerator<T> interface has some further differences from the IEnumerator interface; it does not contain a Reset method but extends the IDisposable interface.

Chapter 19 Enumerating Collections

357

Manually Implementing an Enumerator

In the next exercise, you will define a class that implements the generic IEnumerator<T> interface and create an enumerator for the binary tree class that you built in Chapter 18, “Introducing Generics.” In Chapter 18, you saw how easy it is to traverse a binary tree and display its contents. You would therefore be inclined to think that defining an enumerator that retrieves each element in a binary tree in the same order would be a simple matter. Sadly,

you would be mistaken. The main problem is that when defining an enumerator you need to remember where you are in the structure so that subsequent calls to the MoveNext method

can update the position appropriately. Recursive algorithms, such as that used when walking a binary tree, do not lend themselves to maintaining state information between method calls in an easily accessible manner. For this reason, you will first preprocess the data in the binary tree into a more amenable data structure (a queue) and actually enumerate this data structure instead. Of course, this deviousness is hidden from the user iterating through the elements of the binary tree!

Create the TreeEnumerator class

1.Start Microsoft Visual Studio 2008 if it is not already running.

2.Open the BinaryTree solution located in the \Microsoft Press\Visual CSharp Step by Step\Chapter 19\BinaryTree folder in your Documents folder. This solution contains a working copy of the BinaryTree project you created in Chapter 18.

3.Add a new class to the project: On the Project menu, click Add Class, select the Class template, type TreeEnumerator.cs in the Name text box, and then click Add.

4.The TreeEnumerator class will generate an enumerator for a Tree<TItem> object. To

ensure that the class is typesafe, you must provide a type parameter and implement the IEnumerator<T> interface. Also, the type parameter must be a valid type for the Tree<TItem> object that the class enumerates, so it must be constrained to implement the IComparable<TItem> interface.

In the Code and Text Editor window displaying the TreeEnumerator.cs file, modify the definition of the TreeEnumerator class to satisfy these requirements, as shown in bold type in the following example.

class TreeEnumerator<TItem> : IEnumerator<TItem> where TItem : IComparable<TItem>

{

}

358Part III Creating Components

5.Add the following three private variables shown in bold type to the

TreeEnumerator<TItem> class:

class TreeEnumerator<TItem> : IEnumerator<TItem> where TItem : IComparable<TItem>

{

private Tree<TItem> currentData = null; private TItem currentItem = default(TItem); private Queue<TItem> enumData = null;

}

The currentData variable will be used to hold a reference to the tree being enumerated, and the currentItem variable will hold the value returned by the Current property. You will populate the enumData queue with the values extracted from the nodes in the tree, and the MoveNext method will return each item from this queue in turn. The default keyword is explained in the section titled “Initializing a Variable Defined with a

Type Parameter” later in this chapter.

6.Add a TreeEnumerator constructor that takes a single Tree<TItem> parameter called data. In the body of the constructor, add a statement that initializes the currentData variable to data:

class TreeEnumerator<TItem> : IEnumerator<TItem> where TItem : IComparable<TItem>

{

public TreeEnumerator(Tree<TItem> data)

{

this.currentData = data;

}

...

}

7.Add the following private method, called populate, to the TreeEnumerator<TItem> class immediately after the constructor:

private void populate(Queue<TItem> enumQueue, Tree<TItem> tree)

{

if (tree.LeftTree != null)

{

populate(enumQueue, tree.LeftTree);

}

enumQueue.Enqueue(tree.NodeData);

if (tree.RightTree != null)

{

populate(enumQueue, tree.RightTree);

}

}

This method walks a binary tree, adding the data it contains to the queue. The algorithm used is similar to that used by the WalkTree method in the Tree<TItem> class,

which was described in Chapter 18. The main difference is that rather than the method outputting NodeData values to the screen, it stores these values in the queue.

Chapter 19 Enumerating Collections

359

8.Return to the definition of the TreeEnumerator<TItem> class. Right-click anywhere in the IEnumerator<TItem> interface in the class declaration, point to Implement Interface, and then click Implement Interface Explicitly.

This action generates stubs for the methods of the IEnumerator<TItem> interface and the IEnumerator interface and adds them to the end of the class. It also generates the Dispose method for the IDisposable interface.

Note The IEnumerator<TItem> interface inherits from the IEnumerator and IDisposable

interfaces, which is why their methods also appear. In fact, the only item that belongs to the IEnumerator<TItem> interface is the generic Current property. The MoveNext and Reset methods belong to the nongeneric IEnumerator interface. The IDisposable interface

was described in Chapter 14, “Using Garbage Collection and Resource Management.”

9.Examine the code that has been generated. The bodies of the properties and methods contain a default implementation that simply throws a NotImplementedException. You will replace this code with a real implementation in the following steps.

10.Replace the body of the MoveNext method with the code shown in bold type here:

bool System.Collections.IEnumerator.MoveNext()

{

if (this.enumData == null)

{

this.enumData = new Queue<TItem>(); populate(this.enumData, this.currentData);

}

if (this.enumData.Count > 0)

{

this.currentItem = this.enumData.Dequeue(); return true;

}

return false;

}

The purpose of the MoveNext method of an enumerator is actually twofold. The first

time it is called, it should initialize the data used by the enumerator and advance to the first piece of data to be returned. (Prior to MoveNext being called for the first time, the value returned by the Current property is undefined and should result in an exception.)

In this case, the initialization process consists of instantiating the queue and then calling the populate method to fill the queue with data extracted from the tree.

Subsequent calls to the MoveNext method should just move through data items until

there are no more left, dequeuing items from the queue until the queue is empty in this example. It is important to bear in mind that MoveNext does not actually return data items—that is the purpose of the Current property. All MoveNext does is update

360 Part III Creating Components

internal state in the enumerator (the value of the currentItem variable is set to the data item extracted from the queue) for use by the Current property, returning true if there is a next value and false otherwise.

11. Modify the definition of the get accessor of the generic Current property as follows:

TItem IEnumerator<TItem>.Current

{

get

{

if (this.enumData == null)

throw new InvalidOperationException

(“Use MoveNext before calling Current”);

return this.currentItem;

}

}

Important Be sure to add the code to the correct implementation of the Current property. Leave the nongeneric version, System.Collections.IEnumerator.Current, with its

default implementation.

The Current property examines the enumData variable to ensure that MoveNext has been called. (This variable will be null prior to the first call to MoveNext.) If this is not the case, the property throws an InvalidOperationException—this is the conventional

mechanism used by .NET Framework applications to indicate that an operation cannot be performed in the current state. If MoveNext has been called beforehand, it will have updated the currentItem variable, so all the Current property needs to do is return the

value in this variable.

12.Locate the IDisposable.Dispose method. Comment out the throw new NotImplementedException(); statement as follows in bold type. The enumerator does not use any resources that require explicit disposal, so this method does not

need to do anything. It must still be present, however. For more information about the Dispose method, refer to Chapter 14.

void IDisposable.Dispose()

{

// throw new NotImplementedException();

}

13. Build the solution, and fix any errors that are reported.

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