简体   繁体   English

使用IEnumertor或IEnumerable c#接口?

[英]use IEnumertor or IEnumerable c# interface?

I am porting some Java code to C# and my question is 我正在将一些Java代码移植到C#,我的问题是

One of my Java class declarations looks like this: 我的一个Java类声明如下所示:

private class PseudoEnumeration implements Enumeration

Should this be translated to 应该翻译成

private class PseudoEnumeration : IEnumerator

or 要么

private class PseudoEnumeration : IEnumerable

and why each case? 为什么每个案例?

Another thing is that the enumerator classes work differently in java and C#. 另一件事是枚举器类在java和C#中的工作方式不同。 Java has "hasMoreElements" and "nextElement" while C# uses "MoveNext" and "Current". Java有“hasMoreElements”和“nextElement”,而C#使用“MoveNext”和“Current”。

How would I port a Java function of this form to C#? 如何将此表单的Java函数移植到C#?

public boolean hasMoreElements() {
        return (field.hasMoreElements() );
    }

EDIT: I know MoveNext returns Bool if field has no more elements. 编辑:我知道如果字段没有更多的元素,MoveNext返回Bool。 However, it also advances the field to the enumerator to the next element. 但是,它还将字段推进到枚举器到下一个元素。 How do I just check if it has more elements without advancing the enumerator? 如何在不推进枚举器的情况下检查是否有更多元素?

Given the current Enumeration implementation in Java, you should implement the IEnumerator<T> class , which is the class that enumerates over a collection and provides the methods better fitted to the Java counterpart. 给定Java中的当前Enumeration实现,您应该实现IEnumerator<T> ,该类是枚举集合的类,并提供更适合Java对应的方法。

MoveNext for example returns bool whether there actually is a next value in the enumeration, and relates to the hasMoreElements method of Java's Enumeration . 例如, MoveNext返回bool是否在枚举中确实存在下一个值,并且与Java的EnumerationhasMoreElements方法相关。

The IEnumerable<T> interface does not expose any of the details regarding the current state of the enumeration, like Current or MoveNext ; IEnumerable<T>接口不会公开有关枚举当前状态的任何详细信息,如CurrentMoveNext ; it only exposes a GetEnumerator method that returns an IEnumerator<T> implementation for the given IEnumerable<T> . 它只公开一个GetEnumerator方法,该方法返回给定IEnumerable<T>IEnumerator<T>实现。

Hence, it is the IEnumerator<T> class the one that exposes how to iterate over the collection, the current element, and whether there are more, similar to the Enumeration interface in Java. 因此,它 IEnumerator<T>类暴露如何通过收集,当前元素迭代之一,是否有更多的,类似于Enumeration在Java接口。

如果你有一个枚举的特定类型,它应该实现IEnumerable<T>

In C# if you want to look at next element without advancing the enumerator. 在C#中,如果你想在不推进枚举器的情况下查看下一个元素。

LinkedList will give more control while you are looping 循环时,LinkedList将提供更多控制

You can also use Queue but be careful with this collection because every call to dequeue removes item from list. 您也可以使用Queue,但要小心这个集合,因为每次调用dequeue都会从列表中删除项目。 this collection has peek method. 这个系列有窥视方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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