Created
September 10, 2013 18:32
-
-
Save gscattolin/6513577 to your computer and use it in GitHub Desktop.
Collection, IEnumerable, GetEnumerator, IEnumerator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Example adapted from MSDN showing how to use IEnumerable and IEnumerator | |
| public class CollectionTestItem | |
| { | |
| public CollectionTestItem(string Name, double Value) | |
| { | |
| this.Name = Name; | |
| this.Value = Value; | |
| } | |
| public string Name; | |
| public double Value; | |
| } | |
| public class CollectionTest : IEnumerable | |
| { | |
| private CollectionTestItem[] m_items; | |
| public CollectionTest(CollectionTestItem[] pArray) | |
| { | |
| m_items = new CollectionTestItem[pArray.Length]; | |
| for (int i = 0; i < pArray.Length; i++) | |
| { | |
| m_items[i] = pArray[i]; | |
| } | |
| } | |
| IEnumerator IEnumerable.GetEnumerator() | |
| { | |
| return new CollectionTestEnum(m_items); | |
| } | |
| } | |
| public class CollectionTestEnum : IEnumerator | |
| { | |
| public CollectionTestItem[] m_items; | |
| // Enumerators are positioned before the first element | |
| // until the first MoveNext() call. | |
| int position = -1; | |
| public CollectionTestEnum(CollectionTestItem[] list) | |
| { | |
| m_items = list; | |
| } | |
| public bool MoveNext() | |
| { | |
| position++; | |
| return (position < m_items.Length); | |
| } | |
| public void Reset() | |
| { | |
| position = -1; | |
| } | |
| public object Current | |
| { | |
| get | |
| { | |
| try | |
| { | |
| return m_items[position]; | |
| } | |
| catch (IndexOutOfRangeException) | |
| { | |
| throw new InvalidOperationException(); | |
| } | |
| } | |
| } | |
| } | |
| public class CollectionTestExample | |
| { | |
| public void TryThisExample() | |
| { | |
| CollectionTestItem[] itemArray = new CollectionTestItem[3] | |
| { | |
| new CollectionTestItem("A", 1), | |
| new CollectionTestItem("B", 2), | |
| new CollectionTestItem("C", 3), | |
| }; | |
| CollectionTest itemList = new CollectionTest(itemArray); | |
| foreach (CollectionTestItem p in itemList) | |
| Console.WriteLine(p.Name + " " + p.Value); | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment