foreachã®å±é
Array(ã®æ´¾ç)ã¯ã©ã¹ã¯forã«å±éããããã§ãããæ°ã¥ãã¾ããã§ããã(^^;
using System; using System.Collections; static class Program { static void Main () { int[] arr = { 1, 3, 5, 7, 9}; foreach (int n in arr) Console.WriteLine (n); // foreachã¯å ¨ã¦ãã®ããã«å±éãããã¨æã£ã¦ãããã© IEnumerator e = arr.GetEnumerator (); while (e.MoveNext ()) Console.WriteLine (e.Current); // Arrayã¯ã©ã¹ã¯forã«å±éãããã¿ãã for (int i = 0; i < arr.Length; ++i) Console.WriteLine (arr [i]); } }
ãã¨ãforeachã¯IEnumerableã¤ã³ã¿ãã§ã¼ã¹ããæ´¾çããªãã¦ãGetEnumeratorã¡ã½ããããããã°è¯ããã§ããããããæ°ã¥ãã¾ããã§ããã(^^;
using System; using System.Collections.Generic; class Foo { public IEnumerator<int> GetEnumerator () { for (int i = 0; i < 10; ++i) yield return i; } } class Program { static void Main () { foreach (int n in new Foo ()) Console.WriteLine (n); } }
ãããIEnumerableã¤ã³ã¿ãã§ã¼ã¹ãå¿ é ã ã£ãããIEnumerable<T>ãIEnumerableããæ´¾çãã¦ããã®ã§ã
using System; using System.Collections; using System.Collections.Generic; class Foo : IEnumerable<int> { public IEnumerator<int> GetEnumerator () { for (int i = 0; i < 10; ++i) yield return i; } IEnumerator IEnumerable.GetEnumerator () { for (int i = 0; i < 10; ++i) yield return i; } }
IEnumerable.GetEnumerator()ã¨IEnumerable<T>.GetEnumerator()ã®ä¸¡æ¹ãå®è£ ããå¿ è¦åºã¦ãã¦é¢åã§ãããã(^^;