In order an class support foreach statement, it should support GetEnumerator(), MoveNext(), Reset(), Current() Method.
The interface IEnumerator has the method of MoveNext(), Reset(), Current(), and the interface IEnumerable has the method GetEnumerator().
The ICollection, IList interface are derived from IEnumerable and support GetEnumerator() method.
so,
public class MyClass: ICollection, IEnumerator
{}
MyClass A=new MyClass()
foreach(object a in A)....
So ICollection, IList only will not ensure that your collection class support foreach iteration.
We can write MoveNext(), Reset(), Current() in our custom class to support foreach:
class MyIterator
{
int _count;
public MyIterator(int count)
{
_count=count;
}
public string Current { get { return "Hello World!"; } }
public bool MoveNext()
{
if(_count-- > 0)
return true;
return false;
}
}
Class MyCollection
{
public MyIterator GetEnumerator() { return new MyIterator(3); }
}
class Program
{
static void Main(string[] args)
{
foreach (string value in new MyCollection())
Console.WriteLine(value);
}
}
No comments:
Post a Comment