java Java中Iterator的c#等价物是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1581810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:10:41  来源:igfitidea点击:

what is the c# equivalent of Iterator in Java

c#javaiterator

提问by peter.murray.rust

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

我手动将 Java 转换为 C# 并具有以下代码:

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?

是否有Iterator<T>C# 中的等价物,或者是否有更好的 C# 习惯用法?

回答by Lee

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

C# 中的直接等价物是IEnumerator<T>,代码看起来像这样:

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 GetSGroupIteratorreturn an IEnumerable<T>(and probably rename it to GetSGroups()or similar).

GetSGroupIterator返回一个IEnumerable<T>(并且可能将其重命名为GetSGroups()或类似)。

回答by casperOne

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.

通常在 .NET 中,您将使用该IEnumerable<T>接口。这将返回一个IEnumerator<T>,您可以调用 MoveNext 方法和 Current 属性来遍历序列。

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

在 C# 中,foreach 关键字会为您完成所有这些工作。可以在此处找到如何使用 foreach 的示例:

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

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

回答by Andrew Keith

Yes, in C#, its called an Enumerator.

是的,在 C# 中,它被称为Enumerator

回答by Marek

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

尽管 C# 通过 IEnumerator/IEnumerable 支持这一点,但还有一个更好的习惯用法:foreach

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

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

有关详细信息,请参阅 MSDN:http: //msdn.microsoft.com/en-us/library/aa664754(VS.71).aspx