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


上一篇:idea和eclipse的区别是什么

下一篇:labview怎么清空文件内容


C#
Copyright © 2002-2019 测速网 https://www.inhv.cn/ 皖ICP备2023010105号 城市 地区 街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!
热门搜索