C#中怎么使用迭代器来遍历集合

   2024-10-27 9090
核心提示:在C#中,可以使用迭代器来遍历集合。迭代器是一种特殊的方法,它允许我们按顺序访问集合中的元素,而不必暴露集合的内部实现细节

在C#中,可以使用迭代器来遍历集合。迭代器是一种特殊的方法,它允许我们按顺序访问集合中的元素,而不必暴露集合的内部实现细节。

使用迭代器遍历集合的步骤如下:

在集合类中实现一个返回迭代器的方法,通常命名为GetEnumerator(),并且返回一个实现了IEnumerable接口的迭代器对象。

在迭代器对象中,使用yield关键字来返回集合中的元素。yield关键字可以将当前方法转换为一个迭代器,从而可以在每次循环迭代时返回一个元素。

在调用方代码中使用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对象,打印出每个整数元素。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号