TAILIEUCHUNG - Apress accelerared C# 2010_6

Tham khảo tài liệu 'apress accelerared c# 2010_6', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | CHAPTER 9 ARRAYS COLLECTION TYPES AND ITERATORS if index return false else current index return true public void Reset current default T index 0 public void Dispose try current default T index . finally private MyColl T coll private T current private int index private T items public class EntryPoint static void Main MyColl int integers new MyColl int new int 1 2 3 4 foreach int n in integers n Note In most real-world cases you would derive your custom collection class from Collection T and get the IEnumerable T implementation for free. This example initializes the internal array within MyColl T with a canned set of integers so that the enumerator will have some data to play with. Of course a real container should implement 266 CHAPTER 9 ARRAYS COLLECTION TYPES AND ITERATORS ICollection T to allow you to populate the items in the collection dynamically. The foreach statements expand into code that obtains an enumerator by calling the GetEnumerator method on the IEnumerable T interface. The compiler is smart enough to use IEnumerator T .GetEnumerator rather than in this case. Once it gets the enumerator it starts a loop where it first calls MoveNext and then initializes the variable n with the value returned from Current. If the loop contains no other exit paths the loop will continue until MoveNext returns false. At that point the enumerator finishes enumerating the collection and you must call Reset on the enumerator in order to use it again. Even though you could create and use an enumerator explicitly I recommend that you use the foreach construct instead. You have less code to write which means fewer opportunities to introduce inadvertent bugs. Of course you might have good reasons to manipulate the enumerators directly. For example your enumerator could implement special methods specific to your concrete enumerator type that you need to .

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.