C # foreach implementation,

Source: Internet
Author: User

C # foreach implementation,

Code 1:

        static void Main(string[] args)        {            int[] hs = { 1,2,3,4,5,6,7,8,9};            foreach (int item in hs)            {                Console.WriteLine(item.ToString());            }            Console.ReadKey();        }

Code 2:

        static void Main(string[] args)        {            ArrayList ArrLst = new ArrayList();            ArrLst.AddRange(new string[] { "jack","rose","joy","kristina"});            foreach (string s in ArrLst)            {                Console.WriteLine(s);            }            Console.ReadKey();        }

Code 3:

Using System; using System. collections; using System. collections. generic; using System. linq; using System. text; namespace ForeachDemo {class Dog {// constructor public Dog (params string [] dogNames) {DogNames. addRange (dogNames) ;}// name field and attribute private string Name; public string name {get {return name ;}set {name = value ;}} // List <string> Number of elements in the set public int DogNamesCounts () {return DogNames. count;} public List <string> DogNames = new List <string> (); // The public string this [int index] {get {return DogNames [index];} set {if (index> = DogNames. count) {DogNames. add (value) ;}else {DogNames [index] = value ;}}} class Program {static void Main (string [] args) {Dog D = new Dog ("husky", "GIWA", "Tibetan mastiff", "Shepherd Dog "); // for loop can access the object through the cited device // for (int I = 0; I <D. dogNames. count; I ++) // {// Console. writeLine (D [I]. toString (); // foreach cannot traverse foreach (string s in D) {Console. writeLine (s);} Console. readKey ();}}}

Q: Why can code 1 and Code 2 traverse int array elements through foreach loop?

Why code 3 cannot be accessed through foreach loop Traversal

Cause:

1. The Dog class does not implement the IEnumerable interface (in fact, you only need to have an enumerator method: public IEnumerator GetEnumerator ())

2. You must have a class to implement the IEnumerator interface.

See the following code:

Using System; using System. collections; using System. collections. generic; using System. linq; using System. text; namespace ForeachDemo {class Dog: IEnumerable {// constructor public Dog (params string [] dogNames) {DogNames. addRange (dogNames) ;}// name field and attribute private string Name; public string name {get {return name ;}set {name = value ;}} // List <string> Number of elements in the set public int DogNamesCounts () {return DogNames. count;} public List <string> DogNames = new List <string> (); // The public string this [int index] {get {return DogNames [index];} set {if (index> = DogNames. count) {DogNames. add (value) ;}else {DogNames [index] = value ;}}// here an IEnumerator-type object return value (IEnumerable explicitly) // IEnumerator IEnumerable. getEnumerator () // {// throw new NotImplementedException (); //} public IEnumerator GetEnumerator () {return new DogEnumerator (this. dogNames) ;}} public class DogEnumerator: IEnumerator {/* explicitly implements the IEnumerator interface object IEnumerator. current {get {throw new NotImplementedException () ;}} bool IEnumerator. moveNext () {throw new NotImplementedException ();} void IEnumerator. reset () {throw new NotImplementedException ();} * // constructor public DogEnumerator (List <string> paramDogNames) {this. dogsNames = paramDogNames;} List <string> dogsNames = new List <string> (); // The initial index of the enumerator, private int index =-1; // obtain the Current public object Current {get {if (index <0) {return null;} else {return dogsNames [index] ;}} in the Set // determine whether the number of enumerations can be pushed to the next element of the set public bool MoveNext () {index + = 1; if (index> = dogsNames. count) {return false;} else {return true ;}// set the number of enumerations to its initial position before the first element in the Set (the index is-1) public void Reset () {this. index =-1 ;}} class Program {static void Main (string [] args) {Dog D = new Dog ("husky", "GIWA", "Tibetan mastiff ", "sheepdog"); // for loop can access the object through the cited device // for (int I = 0; I <D. dogNames. count; I ++) // {// Console. writeLine (D [I]. toString (); //} foreach (string s in D) {Console. writeLine (s);} Console. readKey ();}}}

 

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.