TAILIEUCHUNG - Apress-Visual CSharp 2010 Recipes A Problem Solution Approach_6

Thực hiện một lớp học tư nhân bên trong trong các loại đếm được thực hiện Ienumerator giao diện và có thể lặp qua các loại đếm được trong khi vẫn duy trì thông tin trạng thái phù hợp. Trong phương pháp GetEnumerator của các loại đếm, tạo ra và trả về một thể hiện của lớp Iterator. | CHAPTER 13 COMMONLY USED INTERFACES AND PATTERNS 13-5. Implement an Enumerable Type Using a Custom Iterator Problem You need to create an enumerable type but do not want to rely on the built-in iterator support provided by the .NET Framework described in recipe 13-4 . Solution Implement the interface on your collection type. The GetEnumerator method of the lEnumerable interface returns an enumerator which is an object that implements the interface . The lEnumerator interface defines the methods used by the foreach statement to enumerate the collection. Implement a private inner class within the enumerable type that implements the interface IEnumerator and can iterate over the enumerable type while maintaining appropriate state information. In the GetEnumerator method of the enumerable type create and return an instance of the iterator class. How It Works The automatic iterator support built into C is very powerful and will be sufficient in the majority of cases. However in some cases you may want to take direct control of the implementation of your collection s iterators. For example you may want an iterator that supports changes to the underlying collection during enumeration. Whatever your reason the basic model of an enumerable collection is the same as that described in recipe 13-4. Your enumerable type should implement the IEnumerable interface which requires you to implement a method named GetEnumerator. However instead of using the yield return statement in GetEnumerator you must instantiate and return an object that implements the IEnumerator interface. The IEnumerator interface provides a read-only forward-only cursor for accessing the members of the underlying collection. Table 13-2 describes the members of the IEnumerator interface. The IEnumerator instance returned by GetEnumerator is your custom iterator the object that actually supports enumeration of the collection s data elements. 640 .

TỪ KHÓA LIÊN QUAN
Đã 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.