[英]what is the c# equivalent of Iterator in Java
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? 在C#中是否有等效的Iterator<T>
,还是有更好的C#成语?
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 GetSGroupIterator
return an IEnumerable<T>
(and probably rename it to GetSGroups()
or similar). 并让GetSGroupIterator
返回一个IEnumerable<T>
(并可能将其重命名为GetSGroups()
或类似)。
In .NET in general, you are going to use the IEnumerable<T>
interface. 在.NET中,您将使用IEnumerable<T>
接口。 This will return an IEnumerator<T>
which you can call the MoveNext method and Current property on to iterate through the sequence. 这将返回一个IEnumerator<T>
,您可以调用MoveNext方法和Current属性来迭代序列。
In C#, the foreach keyword does all of this for you. 在C#中,foreach关键字为您完成所有这些操作。 Examples of how to use foreach can be found here: 有关如何使用foreach的示例,请访问:
http://msdn.microsoft.com/en-us/library/ttw7t8t6(VS.80).aspx 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 即使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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.