• ADADADADAD

    C#中怎么使用迭代器来遍历集合[ 编程知识 ]

    编程知识 时间:2024-12-04 13:00:56

    作者:文/会员上传

    简介:

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

    以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。

    在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对象,打印出每个整数元素。

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

    将本文的Word文档下载到电脑

    推荐度:

    下载
    热门标签: c