To enable an iterator for a class, simply add GetEnumerator() method which return IEnumerator interface to that class.
Note that you'll need a list-type member (Array, ArrayList, LinkedList,...) that you want to loop through in your list.
Within that method, loop through the list and return each item on each loop.
Example:
#region VideoGame item
public struct VideoGame{
private string asin;
private string title;
public string ASIN{
set{ asin = value; }
get{ return asin; }
}
public string Title{
set{ title = value; }
get{ return title; }
}
}
#endregion
#region VideoGame collection class
public class VideoGameCollection{
private LinkedList m_VideoGameLinkedList = new LinkedList();
public VideoGameCollection{
// Default constructor.
}
public int Count{
get{ return m_VideoGameLinkedList.Count; }
}
public void Add(VideoGame vdoGame){
m_VideoGameLinkedList.AddLast(vdoGame);
}
public IEnumerator GetEnumerator(){
foreach(VideoGame game in m_VideoGameLinkedList){
yield return game;
}
}
The colored lines are the key to enable "foreach" function to your class.
Please note that this requires System.Collections namespace.
Note that for the GetEnumerator() method, just return m_VideoGameLinedList.GetEnumerator(); should do the job.
I will get back again for an update.
|