IEnumerable is a collection, IEnumerator is a collection of iterators

Source: Internet
Author: User

We often IEnumerable, but ignore IEnumerator. Simply put, IEnumerable is a collection that can be iterated through, and IEnumerator implements a loop traversal.

The interfaces are:

public interface IEnumerator
{
    BOOL MoveNext ();
    Object Current{get;}
    void Reset ();
}
public interface IEnumerable
{
    IEnumerator GetEnumerator ();
}

To perform such a simple console program.

    Class Program
    {
        static void Main (string[] args)
        {
            IEnumerable<string> list = new List<string>() {" Hello "," World "};
            foreach (var item in list)
            {
                Console.WriteLine (item);
            }
            Console.readkey ();
        }
    }

In Solution Explorer, right-click the console project and tap Open file in File Explorer.

Tap the bin and then click the Debug folder.

Copy the current file directory.

Open the developer command prompt.

Because the application file is in the F drive, enter the following:

Directed to the directory you just assigned, enter the following:

To view the list in the current directory, enter the following:

Use. NET ILDASM decompile the application file and enter it into a txt text. Enter as follows:

Open a 1.txt file and enter the following:

The 1.txt file is opened with the associated IL code as follows:

As can be seen, foreach is also a syntactic sugar, which is actually a method of invoking IEnumerable's IEnumerator when using a foreach loop.

So, for foreach, you can change the way you do it:

    Class Program
    {
        static void Main (string[] args)
        {
            IEnumerable<string> list = new List<string>() {" Hello "," World "};
            IEnumerator it = list. GetEnumerator ();
            while (it. MoveNext ())
            {
                Console.WriteLine (it. Current);
            }
            Console.readkey ();
        }
    }

IEnumerable is a collection, IEnumerator is a collection of iterators

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.