[C # Basics] necessary conditions and custom set of foreach

Source: Internet
Author: User

Introduction I recently reviewed my previous study notes and saw foreach. I remember that when I was talking to my teacher, I was a little confused and didn't quite understand it. This is like, when I was in elementary school, you wouldn't just say that, but with the increase of time, you will not be conscious of it, and you will learn a little truth. Some things you didn't know at the time, but as your experience and experience grow, one day you will suddenly realize that, oh, it turns out to be like this. The custom collection class mentioned foreach has to say the set, so we should start with the custom set first. Copy the Code 1 using System; 2 using System. collections. generic; 3 using System. linq; 4 using System. text; 5 using System. threading. tasks; 6 7 namespace Wolfy. custom set 8 {9 /// <summary> 10 // custom set class 11 /// </summary> 12 public class MyArrayList13 {14 // <summary> 15 /// increase the capacity attribute of the set by a multiple of 0, 4, 8, and read-only 16 /// </summary> 17 public int Capacity18 {19 get20 {21 return this. objArray. length = 0? 0: this. index> this. objArray. Length? This. objArray. length * 2: this. objArray. length; 22} 23} 24 // <summary> 25 // the actual number of elements in the set and read-only 26 /// </summary> 27 public int Count28 {29 get30 {31 return this. index; 32} 33} 34 private int index; 35 private object [] objArray; 36 public MyArrayList () 37 {38 index = 0; 39 // Initialize an array of 0 lengths 40 this. objArray = new object [0]; 41} 42 // <summary> 43 // Add element 44 // </summary> 45 // <param name = "value"> element value </param> 46 publ Ic void Add (object value) 47 {48 if (index> = this. objArray. Length) 49 {50 object [] newArray = index = 0? New object [this. objArray. length + 4]: new object [this. objArray. length * 2]; 51 objArray. copyTo (newArray, 0); 52 objArray = newArray; 53 objArray [index ++] = value; 54} 55 else56 {57 objArray [index ++] = value; 58} 59} 60 // <summary> 61 // Add an array 62 // </summary> 63 // <param name = "objs"> </param> 64 public void AddRange (object [] objs) 65 {66 for (int I = 0; I <objs. length; I ++) 67 {68 this. add (objs [I]); 69} 70} 71} 72} the copied Code does not know whether the custom set and ArrayList are the same. You can simply test them. Copy the Code 1 using System; 2 using System. collections; 3 using System. collections. generic; 4 using System. linq; 5 using System. text; 6 using System. threading. tasks; 7 8 namespace Wolfy. custom set 9 {10 class Program11 {12 static void Main (string [] args) 13 {14 ArrayList list = new ArrayList (); 15 // MyArrayList list = new MyArrayList (); 16 Console. writeLine ("count:" + list. count); 17 Console. writeLine ("Capacity :" + List. capacity); 18 list. add (1); 19 list. add (1); 20 Console. writeLine ("count:" + list. count); 21 Console. writeLine ("Capacity:" + list. capacity); 22 list. add (1); 23 list. add (1); 24 list. add (1); 25 Console. writeLine ("count:" + list. count); 26 Console. writeLine ("Capacity:" + list. capacity); 27 list. add (1); 28 list. add (1); 29 list. add (1); 30 list. add (1); 31 list. add (1); 32 list. add (1); 33 Console. writeLine ("count :" + List. count); 34 Console. writeLine ("Capacity:" + list. capacity); 35 object [] arr = {1, 2, 3, 4, 5, 6}; 36 list. addRange (arr); 37 Console. writeLine ("count:" + list. count); 38 Console. writeLine ("Capacity:" + list. capacity); 39 Console. read (); 40} 41} 42} copy the code.. Net. Result: The Custom set. Result: The output result is the same. Now, use foreach to traverse and customize the elements in the set. F6 compilation, an error will be prompted. In fact, how does a foreach statement work? As we all know, in foreach, the objects following the in should implement the IEnumerable interface. When the program runs, the essence is to call the GetEnumerator function of IEnumerable to return an IEnumerator object. foreach uses the Current of the IEnumerator object, the MoveNext and Reset members can enumerate a piece of data. Simple code implementation: 1 // System. IEnumerator2 IEnumerator enumerator = this. objArray. getEnumerator (); 3 while (enumerator. moveNext () 4 {5 Console. writeLine (enumerator. current); 6} Put the code in the Custom set, define a method GetArray (), then test the copy code 1 /// <summary> 2 /// get all elements 3 /// </summary> 4 public void GetArray () 5 {6 // System. IEnumerator 7 IEnumerator enumerator = this. objArray. getEnumerator (); 8 while (Enumerator. moveNext () 9 {10 Console. write (enumerator. current + ","); 11} 12} copy the code Test Result: you will find many more commas (,) during running, because after execution, the enumerator is not Dispose, IEnumerator that inherits IDisposable will be correctly processed after foreach ends (call the Dispose method ). To implement the IEnumerable interface in a custom set, the IEnumerable interface must implement the GetEnumerator () method in it: 1 public IEnumerator GetEnumerator () 2 {3 throw new NotImplementedException (); 4} the return value of this method is the object of the class implementing the IEnumerator interface. Now you need to define a class that implements this interface. Copy the Code 1 using System; 2 using System. collections; 3 using System. collections. generic; 4 using System. linq; 5 using System. text; 6 using System. threading. tasks; 7 8 namespace Wolfy. custom set 9 {10 public class MyEnumerator: IEnumerator11 {12 // <summary> 13 // return the value of the element pointed to by the current pointer 14 /// </summary> 15 public object Current16 {17 get {throw new NotImplementedException ();} 18} 19 /// <summary> 20 // move the pointer one bit forward and Determines whether the current bit has any elements. the pointer is at the-1 position by default. 21 /// </summary> 22 /// <returns> </returns> 23 public bool MoveNext () 24 {25 throw new NotImplementedException (); 26} 27 /// <summary> 28 // Reset 29 /// </summary> 30 public void Reset () 31 {32 throw new NotImplementedException (); 33} 34} 35} copying code iterations requires array parameters. In the constructor, the arrays in the Custom set are passed in. In MoveNext, You need to determine whether the pointer is moved to the end of the array, the length of the array is required. The GetEnumerator () method in MyArrayList implements 1 public IEnumerator GetEnumerator () 2 {3 return new MyEnumerator (this. objArray, this. count); 4} The MyEnumerator class copies the Code 1 using System; 2 using System. collections; 3 using System. collections. generic; 4 using System. linq; 5 using System. text; 6 using System. threading. tasks; 7 8 namespace Wolfy. custom set 9 {10 public class MyEnumerator: IEnumerator11 {12 /// <summary> 13 // default pointer position 14 /// </summary> 15 private int index =-1; 16 private object [] objArray; 17 /// <summary> 18 /// array length 19 /// </summary> 20 private int count; 21 public MyEnumerator (object [] objArray, int count) 22 {23 24 this. objArray = objArray; 25 this. count = count; 26} 27 /// <summary> 28 // return the value of the element pointed to by the current pointer 29 /// </summary> 30 public object Current31 {32 get {return this. objArray [index];} 33} 34 // <summary> 35 // move the pointer to the first position and check whether the current position has any elements. the pointer is 36 at-1 by default. // </summary> 37 // <returns> </returns> 38 public bool MoveNext () 39 {40 index ++; // The pointer first moves one 41 if (index <this. count) 42 {43 return true; 44} 45 else46 {47 return false; 48} 49} 50 // <summary> 51 // Reset 52 // </summary> 53 public void Reset () 54 {55 index =-1; 56} 57} 58}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.