拡張メソッドによるGetEnumerator()
「C# 3.0」foreach should consider GetEnumerator extension method
なるほど、こういう考え方もありますね。
MSの回答によると、
IEnumerableを返すメソッドを呼べば良いのでは?とのこと。
using System; using System.Collections.Generic; class Foo { public List<int> list; public Foo (int n) { list = new List<int>(); for (int i = 0; i < n; ++i) list.Add (i); } } static class Ext { public static IEnumerable<int> GetEnumerator (this Foo foo) { foreach (int n in foo.list) yield return n; } } public class App { public static void Main () { // foreach (int n in new Foo(10)) // このように使いたい foreach (int n in new Foo(10).GetEnumerator ()) Console.WriteLine (n); } }
拡張メソッドを使いすぎるとコードが分かり難くなるのは理解出来ますが、foreachに対応して欲しい気がします。どーせ、foreach自体、シンタックスシュガーなんだし、毒をくらわば・・・(^^;