溫馨提示×

C#中怎么使用迭代器來遍歷集合

c#
小億
147
2024-03-07 10:48:24
欄目: 編程語言

在C#中,可以使用迭代器來遍歷集合。迭代器是一種特殊的方法,它允許我們按順序訪問集合中的元素,而不必暴露集合的內部實現細節。

使用迭代器遍歷集合的步驟如下:

  1. 在集合類中實現一個返回迭代器的方法,通常命名為GetEnumerator(),并且返回一個實現了IEnumerable接口的迭代器對象。

  2. 在迭代器對象中,使用yield關鍵字來返回集合中的元素。yield關鍵字可以將當前方法轉換為一個迭代器,從而可以在每次循環迭代時返回一個元素。

  3. 在調用方代碼中使用foreach循環來遍歷集合中的元素。

下面是一個簡單示例,演示了如何使用迭代器遍歷一個整數集合:

using System;
using System.Collections;
using System.Collections.Generic;

public class MyCollection : IEnumerable<int>
{
    private List<int> list = new List<int>();

    public MyCollection()
    {
        list.Add(1);
        list.Add(2);
        list.Add(3);
        list.Add(4);
    }

    public IEnumerator<int> GetEnumerator()
    {
        foreach (int i in list)
        {
            yield return i;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

class Program
{
    static void Main()
    {
        MyCollection collection = new MyCollection();

        foreach (int i in collection)
        {
            Console.WriteLine(i);
        }
    }
}

在這個示例中,MyCollection類實現了IEnumerable接口,并在GetEnumerator()方法中使用yield關鍵字來返回整數集合中的元素。在Main方法中,我們使用foreach循環遍歷MyCollection對象,打印出每個整數元素。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女