Ienumrator enumerators and IEnumerable interfaces in C #

Source: Internet
Author: User

The enumerator that declares the IEnumerator

To create an enumerator for a non-generic interface, you must declare the class that implements the IEnumerator interface, and the IEnumerator interface has the following characteristics:

1, she is a member of the System.Collections namespace

2, it contains 3 methods current, MoveNext and reset

For example, the following code implements an enumerator class that lists the color array groups:

Using System.Collections;
     
Class Colorenumerator:ienumerator
{
    string [] Colors;    
    int position=-1;
     
    The public object,
    {get
        {
            if (position==-1), return
                new Exception ();
            if (position==colors.length) return the
                new Exception ();
            return colors[position];
        }
     
    public bool MoveNext ()
    {
        if (position<colors.length-1)
        {
            position++;
            return true;
        }
        else
        {return
            false;
        }
    }
     
    pulic void Reset ()
    {
        position=-1
    }
     
    Public Colorenumerator (string[] thecolors)
    {
        colors=new string[thecolors.length];
        for (int i=0;i<thecolors.length;i++)
        {
            colors[i]=thecolors[i];
        }
    }

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/csharp/

The IEnumerable interface has only one member--getenumerator method, which returns an enumerator for the object.

The following code gives an instance of using the Colorenumerator enumerator class above, and remember that Colorenumerator implements IEnumerator.

Class mycolors:ienumerable
{
    string[] colors={"", "", ""};
    Public IEnumerator GetEnumerator ()//Returns an object of type IEnumerator, which is the enumerable type
    {return
        new Colorenumerator (Colors);
    }

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.