. Net iterator

Source: Internet
Author: User

 

    • Iterator
An iterator is a method, get accessor or operator that enables you to support foreach iteration in a class or structure without implementing the entire ienumerable interface. You only need to provide an iterator to traverse the data structure in the class. When the compiler detects the iterator, it automatically generates the current, movenext, and dispose methods for the ienumerable or ienumerable <t> interfaces. An iterator is a sequence that can return values of the same type.Code. The iterator can be used as a method, operator, or get accessors code body. The iterator Code uses the yield return statement to return each element in sequence. Yield break terminates iteration. Multiple iterators can be implemented in the class. Each iterator must have a unique name like any class member and can be called by client code in the foreach statement, as shown below: foreach (int x in sampleclass. iterator2 ){} The return type of the iterator must be ienumerable, ienumerator, ienumerable <t>, or ienumerator <t>.
    • Sample Code
 Public   Class Daysoftheweek: system. Collections. ienumerable { String [] M_days = { "Sun" , "Mon" , "Tue" , "Wed" , "Thr" , "Fri" ,"Sat" }; Public System. Collections. ienumerator getenumerator (){ For ( Int I = 0; I <m_days.length; I ++ ){ Yield   Return M_days [I] ;}} Class Testdaysoftheweek { Static   Void Main () {daysoftheweek week = New Daysoftheweek (); Foreach (String Day In Week) {system. Console. Write (day + "" );}}}

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.