Непонятный момент с IEnumerable - C#
Формулировка задачи:
как это объяснить? неявное наследование от IEnumerable?
using System;
using System.Collections;
class SColl//не наследуемся от IEnumerable
{
int[] arr = {1,2,3};
public IEnumerator GetEnumerator() //если изменить имя, то все поломается
{
return arr.GetEnumerator();
}
}
class Program
{
public static void Main()
{
SColl s = new SColl();
foreach (int i in s) Console.WriteLine(i);//работает
Console.ReadKey(true);
}
}
всё, разобрался. Это называется "утиная типизация"
Решение задачи: «Непонятный момент с IEnumerable»
textual
Листинг программы
class Foo
{
public Bar GetEnumerator()
{
return new Bar();
}
}
struct Bar
{
public string Current { get { return "Hello!"; } }
private bool moveNext = true;
public bool MoveNext()
{
var t = moveNext;
moveNext = false;
return t;
}
}
var foo = new Foo();
foreach (var x in foo)
Console.WriteLine(x);