I've noticed that Java's Iterator
(interface) is similar to C#'s IEnumerable
, but is there any way to use it like this:
private IEnumerable<Label> it;
it = labels.iterator();
In Java I could just do:
private Iterator<JLabel> it;
it = labels.iterator();
What's the C# equivalent of Java's Iterator
interface?
It's not used very often, but the analogy is the IEnumerator<T>
interface:
var enumerator = labels.GetEnumerator();
.NET's IEnumerator
differs from Java's Iterator
with the following:
Iterator
after construction is pointing at the first element of the collection (or, for an empty collection, is invalid and hasNext
will return false
immediately), IEnumerator
points initially before the first element of the collection (for an empty collection MoveNext
will return false
)Iterator
has hasNext
method, while for IEnumerator
you verify the result of MoveNext
method Iterator
has next
method, while for IEnumerator
you also use MoveNext
Iterator
's next
returns the next element, while with IEnumerator
you use Current
property after calling MoveNext
Iterator
in Java has remove
method which allows you to remove elements from the underlying collection. There is no equivalent in IEnumerator
So for Java you'd iterate with something like this:
it = labels.iterator();
while (it.hasNext())
{
elem = it.next();
}
While in C#:
en = labels.GetEnumerator();
while (en.MoveNext())
{
elem = en.Current;
}
Usually, having labels
as a collection (which always implements IEnumerable<T>
) you just use it directly:
foreach (var label in labels)
{
//...
}
And of course, you can store IEnumerable<T>
for later use (names referring to your example):
IEnumerable<Label> it = labels;
Beware, that IEnumerable<T>
is lazy, just like Iterator
in Java.
You can also easily obtain a snapshot of a collection like this (again, it
refers to your example, better name could be chosen):
IEnumerable<Label> it = labels.ToArray();
// or Label[] it = labels.ToArray();
// or better: var it = labels.ToArray();
There is another difference between Java's iterator and .Net's IEnumerable. The former has a previous()
method which the latter lacks.
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.