示例1:
class E { public IEnumerable MyGetEnumerator1() { yield return 1; } public IEnumerable<int> MyGetEnumerator2() { yield return 1; yield return 2; } public IEnumerator MyGetEnumerator3() { yield return 1; yield return 2; yield return 3; } public IEnumerator<int> MyGetEnumerator4() { yield return 1; yield return 2; yield return 3; yield return 4; } public IEnumerator GetEnumerator() { yield return 1; yield return 2; yield return 3; yield return 4; } } E e = new E(); foreach (var item in e.MyGetEnumerator1()) Console.WriteLine(item); foreach (var item in e.MyGetEnumerator2()) Console.WriteLine(item); //报错:foreach statement cannot operate on variables of type 'IEnumerator' because 'IEnumerator' does not contain a public instance or extension definition for 'GetEnumerator' foreach (var item in e.MyGetEnumerator3()) Console.WriteLine(item); //报错:同上 foreach (var item in e.MyGetEnumerator4()) Console.WriteLine(item); //当GetEnumerator()的返回类型为IEnumerator或IEnumerator<int>时都能正常运行,当为IEnumerable或IEnumerable<int>时,则报错:1、'IEnumerable' does not contain a definition for 'Current',2、foreach requires that the return type 'IEnumerable' of 'E.GetEnumerator()' must have a suitable public 'MoveNext' method and public 'Current' property foreach (var item in e) Console.WriteLine(item);
标签:return,IEnumerable,yield,item,IEnumerator,public From: https://www.cnblogs.com/sound-of-wind-rain/p/18438418