How to use a type in FOREACH

Source: Internet
Author: User
1 // enable the class to use 2 public class students 3 {4 int I =-1; 5 6 student [] stus; 7 public students () in the FOREACH Loop () {8 stus = new student [2] {new student ("xx"), new student ("wsenmin") }; 9} 10 public IEnumerator GetEnumerator () 11 {12 return (IEnumerator) this; 13} 14 public object Current15 {16 get {17 return stus [I]; 18} 19 20} 21 public bool MoveNext () 22 {23 I ++; 24 return (I <stus. length); 25} 26 public void Reset () {27 I =-1; 28} 29}

View Code

 

 

GetEnumerator converts a class to IEnumerator

Current returns the Current value

MoveNext sets the current index

Reset Index

            students stus = new students();            foreach (student item in stus)            {                Console.WriteLine(item.Name);            }            stus.Reset();            foreach (student item in stus)            {                Console.WriteLine(item.Name);            }             

View Code

 

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.