방법: 정수 목록에 대한 반복기 블록 만들기(C# 프로그래밍 가이드)
업데이트: 2007년 11월
이 예제에서는 정수 배열을 사용하여 SampleCollection 목록을 만듭니다. for 루프는 컬렉션을 반복하며 각 항목의 값을 반환합니다. 그런 다음 foreach 루프를 사용하여 컬렉션의 항목을 표시합니다.
예제
// Declare the collection:
public class SampleCollection
{
public int[] items;
public SampleCollection()
{
items = new int[5] { 5, 4, 7, 9, 3 };
}
public System.Collections.IEnumerable BuildCollection()
{
for (int i = 0; i < items.Length; i++)
{
yield return items[i];
}
}
}
class MainClass
{
static void Main()
{
SampleCollection col = new SampleCollection();
// Display the collection items:
System.Console.WriteLine("Values in the collection are:");
foreach (int i in col.BuildCollection())
{
System.Console.Write(i + " ");
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
/* Output:
Values in the collection are:
5 4 7 9 3
*/
참고 항목
작업
방법: 제네릭 목록에 대한 반복기 블록 만들기(C# 프로그래밍 가이드)