简体   繁体   中英

what is the c# equivalent of Iterator in Java

I am manually converting Java to C# and have the following code:

for (Iterator<SGroup> theSGroupIterator = SGroup.getSGroupIterator();
     theSGroupIterator.hasNext();)
{
    SGroup nextSGroup = theSGroupIterator.next();
}

Is there an equivalent of Iterator<T> in C# or is there a better C# idiom?

The direct equivalent in C# would be IEnumerator<T> and the code would look something like this:

SGroup nextSGroup;
using(IEnumerator<SGroup> enumerator = SGroup.GetSGroupEnumerator())
{
    while(enumerator.MoveNext())
    {
        nextSGroup = enumerator.Current;
    }
}

However the idiomatic way would be:

foreach(SGroup group in SGroup.GetSGroupIterator())
{
    ...
}

and have GetSGroupIterator return an IEnumerable<T> (and probably rename it to GetSGroups() or similar).

In .NET in general, you are going to use the IEnumerable<T> interface. This will return an IEnumerator<T> which you can call the MoveNext method and Current property on to iterate through the sequence.

In C#, the foreach keyword does all of this for you. Examples of how to use foreach can be found here:

http://msdn.microsoft.com/en-us/library/ttw7t8t6(VS.80).aspx

是的,在C#中,它被称为枚举器

Even though this is supported by C# via IEnumerator/IEnumerable, there is a better idiom: foreach

foreach (SGroup nextSGroup in items)
{
    //...
}

for details, see MSDN: http://msdn.microsoft.com/en-us/library/aa664754(VS.71).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM