Thực hiện một điều tra viên khi sử dụng một Iterator Như bạn thấy, quá trình làm một bộ sưu tập đếm được có thể trở nên phức tạp và có khả năng dễ bị lỗi. Để làm cho cuộc sống dễ dàng hơn, C # 2,0 bao gồm các vòng lặp mà có thể tự động hoá nhiều quá trình này. | Implementing an Enumerator by Using an Iterator As you can see the process of making a collection enumerable can become complex and potentially error-prone. To make life easier C includes iterators which can automate much of this process. According to the C specification an iterator is a block of code that yields an ordered sequence of values. Additionally an iterator is not actually a member of an enumerable class. Rather it specifies the sequence that an enumerator should use for returning its values. In other words an iterator is just a description of the enumeration sequence that the C compiler can use for creating its own enumerator. This concept requires a little thought to understand it properly so let s consider a basic example before returning to binary trees and recursion. A Simple Iterator The BasicCollection T class shown below illustrates the basic principles of implementing an iterator. The class uses a List T for holding data and provides the FillList method for populating this list. Notice also that the BasicCollection T class implements the IEnumerable T interface. The GetEnumerator method is implemented by using an iterator class BasicCollection T IEnumerable T private List T data new List T public void FillList params T items for int i 0 i i items i IEnumerator T IEnumerable T .GetEnumerator for int i 0 i i yield return data i IEnumerator Not implemented in this example The GetEnumerator method appears to be straightforward but bears closer examination. The first thing you should notice is that it doesn t appear to return an IEnumerator T type. Instead it loops through the items in the data array returning each item in turn. The key point is the use of the yield keyword. The yield keyword indicates the value that should be returned by each iteration. If it helps you can think of the yield statement as calling a temporary halt to the method passing back a value to the caller. When