티스토리 뷰
// C# : Iterator
using System;
using System.Collections;
namespace Iteration
{
class Program
{
static void Main(string[] args)
{
DaysOfTheWeek myDays = new DaysOfTheWeek();
IEnumerator myEnumerator = myDays.GetEnumerator();
// When you create an iterator for a class or struct, you don't have to
// implement the whole IEnumerator interface. When the compiler detects
// the iterator, it automatically generates the Current, MoveNext, and
// Dispose methods of the IEnumerator or IEnumerator<T> interface.
while (myEnumerator.MoveNext())
{
Console.WriteLine(myEnumerator.Current);
}
// Iterators don't support the IEnumerator.Reset method.
// To re-iterate from the start, you must obtain a new iterator.
try
{
myEnumerator.Reset(); // Exception occurs
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
// You consume an iterator from client code by using a foreach statement
// or by using a LINQ query.
// The foreach statement implicitly calls the GetEnumerator method.
// foreach is allowed because DaysOfTheWeek implements IEnumerable.
foreach (string item in myDays)
{
Console.WriteLine(item);
}
}
}
class DaysOfTheWeek : IEnumerable
{
private string[] days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
// This method implements the GetEnumerator method.
// It allows an instance of the class to be used in a foreach statement.
public IEnumerator GetEnumerator()
{
for (int index = 0; index < days.Length; index++)
{
// Yield each day of the week.
yield return days[index];
}
}
}
}
/* Output
Sun
Mon
Tue
Wed
Thu
Fri
Sat
Specified method is not supported.
Sun
Mon
Tue
Wed
Thu
Fri
Sat
*/
'Series' 카테고리의 다른 글
Iterator [C#] List<string> animals - GetEnumerator, MoveNext, Current (0) | 2018.06.15 |
---|---|
Iterator [C#] List<string> weekDays - foreach, while, Reset (0) | 2018.06.15 |
Iterator [C#] class Count : IEnumerable<string> - GetEnumerator (0) | 2018.06.15 |
Iterator [C#] class Count : IEnumerable<string> - foreach (0) | 2018.06.15 |
Iterator [C#] class Count : IEnumerable - GetEnumerator (0) | 2018.06.15 |