IEnumerator defines the protocol for traversable or enumerable collections.
Its declaration is as follows:
public interface IEnumerator
{
bool MoveNext();
object Current { get; }
void Reset();
}
IEnumerable is IEnumerator provider:
public interface IEnumerable
{
IEnumerator GetEnumerator();
}
The following example illustrates how to use IEnumerable and IEnumerator:
using System;
using System.Collections;
class Sample
{
public static void Main()
{
string s = "java2s.com";
IEnumerator rator = s.GetEnumerator();
while (rator.MoveNext())
{
char c = (char)rator.Current;
Console.Write(c + ".");
}
}
}
The output:
j.a.v.a.2.s...c.o.m.
C# provides a shortcut: foreach statement.
using System;
using System.Collections;
class Sample
{
public static void Main()
{
string s = "Hello"; // The String class implements IEnumerable
foreach (char c in s) Console.Write(c + ".");
}
}
The output:
H.e.l.l.o.
java2s.com | Contact Us | Privacy Policy |
Copyright 2009 - 12 Demo Source and Support. All rights reserved. |
All other trademarks are property of their respective owners. |