티스토리 뷰


// 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
*/


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함