TAILIEUCHUNG - Enumerator Make Life Easier

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. | 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

TAILIEUCHUNG - Chia sẻ tài liệu không giới hạn
Địa chỉ : 444 Hoang Hoa Tham, Hanoi, Viet Nam
Website : tailieuchung.com
Email : tailieuchung20@gmail.com
Tailieuchung.com là thư viện tài liệu trực tuyến, nơi chia sẽ trao đổi hàng triệu tài liệu như luận văn đồ án, sách, giáo trình, đề thi.
Chúng tôi không chịu trách nhiệm liên quan đến các vấn đề bản quyền nội dung tài liệu được thành viên tự nguyện đăng tải lên, nếu phát hiện thấy tài liệu xấu hoặc tài liệu có bản quyền xin hãy email cho chúng tôi.
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.