Đang chuẩn bị liên kết để tải về tài liệu:
Apress Introducing Dot Net 4 With Visual Studio_4
Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Tham khảo tài liệu 'apress introducing dot net 4 with visual studio_4', công nghệ thông tin, hệ điều hà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 coll.items.Length return false else current coll.items index return true public void Reset current default T index 0 public void Dispose try current default T index coll.items.Length . finally Monitor.Exit coll.items.SyncRoot 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 Console.WriteLine 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 IEnumerator.GetEnumerator 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 .