Пример, который вы опубликовали, является в основном реализацией перечислителя, так что да, это будет работать.
string[] _array = {"foo", "bar", "something", "else", "here"};
IEnumerable<String> GetEnumarable()
{
foreach(string i in _array)
yield return i;
}
Если вы хотите сделать это с пользовательской структурой данных или добавить больше логики при переходе к следующему элементу (то есть, ленивая загрузка, потоковая передача данных), вы можете реализовать интерфейс IEnumerator
самостоятельно.
Пример
public class EnumeratorExample : IEnumerator
{
string[] _array;
// enumerators are positioned before the first element
// until the first MoveNext() call.
int position = -1;
public EnumeratorExample(string[] array)
{
_array = list;
}
public bool MoveNext()
{
++position;
return (position < _array.Length);
}
public void Reset()
{
position = -1;
}
object IEnumerator.Current
{
get { return Current; }
}
public string Current
{
get
{
try
{
return _array[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException("Enumerator index was out of range. Position: " + position + " is greater than " + _array.Length);
}
}
}
}
Ссылки
- IEnumerable Interface