本文主要记录我在学习C#中foreach遍历原理的心得体会。

对集合中的要素进行遍历是所有编码中经常涉及到的操作,因此大部分编程语言都把此过程写进了语法中,比如C#中的foreach。经常会看到下面的遍历代码:
var lstStr = new List<string> { "a", "b" };
foreach (var str in lstStr)
{
Console.WriteLine(str);
}
实际此代码的执行过程:
var lstStr = new List<string> {"a", "b"};
IEnumerator<string> enumeratorLst = lstStr.GetEnumerator();
while (enumeratorLst.MoveNext())
{
Console.WriteLine(enumeratorLst.Current);
}
会发现有GetEnumerator()方法和IEnumerator<string>类型,这就涉及到可枚举类型和枚举器的概念。
为了方便理解,以下为非泛型示例:
// 摘要:
// 公开枚举器,该枚举器支持在非泛型集合上进行简单迭代。
public interface IEnumerable
{
// 摘要:
// 返回一个循环访问集合的枚举器。
//
// 返回结果:
// 可用于循环访问集合的 System.Collections.IEnumerator 对象。
IEnumerator GetEnumerator();
}
实现了此接口的类称为可枚举类型,是可以用foreach进行遍历的标志。
方法GetEnumerator()的返回值是枚举器,可以理解为游标。
// 摘要:
// 支持对非泛型集合的简单迭代。
public interface IEnumerator
{
// 摘要:
// 获取集合中的当前元素。
//
// 返回结果:
// 集合中的当前元素。
//
// 异常:
// System.InvalidOperationException:
// 枚举数定位在该集合的第一个元素之前或最后一个元素之后。
object Current { get; }
// 摘要:
// 将枚举数推进到集合的下一个元素。
//
// 返回结果:
// 如果枚举数成功地推进到下一个元素,则为 true;如果枚举数越过集合的结尾,则为 false。
//
// 异常:
// System.InvalidOperationException:
// 在创建了枚举数后集合被修改了。
bool MoveNext();
//
// 摘要:
// 将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。
//
// 异常:
// System.InvalidOperationException:
// 在创建了枚举数后集合被修改了。
void Reset();
}
以下是自定义一个迭代器的示例(https://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx):
using System;
using System.Collections;
// Simple business object.
public class Person
{
public Person(string fName, string lName)
{
this.firstName = fName;
this.lastName = lName;
}
public string firstName;
public string lastName;
}
// Collection of Person objects. This class
// implements IEnumerable so that it can be used
// with ForEach syntax.
public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length];
for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
}
// Implementation for the GetEnumerator method.
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator) GetEnumerator();
}
public PeopleEnum GetEnumerator()
{
return new PeopleEnum(_people);
}
}
// When you implement IEnumerable, you must also implement IEnumerator.
public class PeopleEnum : IEnumerator
{
public Person[] _people;
// Enumerators are positioned before the first element
// until the first MoveNext() call.
int position = -1;
public PeopleEnum(Person[] list)
{
_people = list;
}
public bool MoveNext()
{
position++;
return (position < _people.Length);
}
public void Reset()
{
position = -1;
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public Person Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
class App
{
static void Main()
{
Person[] peopleArray = new Person[3]
{
new Person("John", "Smith"),
new Person("Jim", "Johnson"),
new Person("Sue", "Rabon"),
};
People peopleList = new People(peopleArray);
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);
}
}
/* This code produces output similar to the following:
*
* John Smith
* Jim Johnson
* Sue Rabon
*
*/
在有了yield这个关键字以后,我们可以通过这样的方式来创建枚举器:
using System;
using System.Collections;
// Simple business object.
public class Person
{
public Person(string fName, string lName)
{
this.firstName = fName;
this.lastName = lName;
}
public string firstName;
public string lastName;
}
// Collection of Person objects. This class
// implements IEnumerable so that it can be used
// with ForEach syntax.
public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length];
for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
}
// Implementation for the GetEnumerator method.
IEnumerator IEnumerable.GetEnumerator()
{
for (int i = 0; i < _people.Length; i++)
{
yield return _people[i];
}
}
}
class App
{
static void Main()
{
Person[] peopleArray = new Person[3]
{
new Person("John", "Smith"),
new Person("Jim", "Johnson"),
new Person("Sue", "Rabon"),
};
People peopleList = new People(peopleArray);
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
# C#
# foreach
# C#中foreach语句使用break暂停遍历的方法
# C#使用foreach语句简单遍历数组的方法
# C#使用foreach遍历哈希表(hashtable)的方法
# C#使用foreach语句遍历队列(Queue)的方法
# C#使用foreach语句遍历二维数组的方法
# C#中用foreach语句遍历数组及将数组作为参数的用法
# C#使用foreach语句遍历堆栈(Stack)的方法
# C#:foreach与yield语句的介绍
# C#中循环语句:while、for、foreach的使用
# C#中foreach语句深入研究
# 遍历
# 第一个
# 迭代
# 涉及到
# 则为
# 进到
# 我在
# 可以用
# 进了
# 我们可以
# 这就
# 自定义
# 为其
# 都把
# 经常会
# 大家多多
# 编程语言
# 返回值
# 实现了
# 发现有
相关文章:
网站制作和推广的区别,想自己建立一个网站做推广,有什么快捷方法马上做好一个网站?
如何高效生成建站之星成品网站源码?
天津个人网站制作公司,天津网约车驾驶员从业资格证官网?
如何快速上传自定义模板至建站之星?
如何制作公司的网站链接,公司想做一个网站,一般需要花多少钱?
如何在新浪SAE免费搭建个人博客?
网站制作新手教程,新手建设一个网站需要注意些什么?
网站制作壁纸教程视频,电脑壁纸网站?
图册素材网站设计制作软件,图册的导出方式有几种?
北京专业网站制作设计师招聘,北京白云观官方网站?
Swift开发中switch语句值绑定模式
广东专业制作网站有哪些,广东省能源集团有限公司官网?
建站之星后台密码遗忘?如何快速找回?
小视频制作网站有哪些,有什么看国内小视频的网站,求推荐?
可靠的网站设计制作软件,做网站设计需要什么样的电脑配置?
如何在阿里云购买域名并搭建网站?
c# Task.ConfigureAwait(true) 在什么场景下是必须的
C#怎么使用委托和事件 C# delegate与event编程方法
如何通过免费商城建站系统源码自定义网站主题与功能?
建设网站制作价格,怎样建立自己的公司网站?
网站制作公司哪里好做,成都网站制作公司哪家做得比较好,更正规?
西安市网站制作公司,哪个相亲网站比较好?西安比较好的相亲网站?
建站之星安装失败:服务器环境不兼容?
如何在景安服务器上快速搭建个人网站?
h5网站制作工具有哪些,h5页面制作工具有哪些?
网站插件制作软件免费下载,网页视频怎么下到本地插件?
如何配置WinSCP新建站点的密钥验证步骤?
网页设计网站制作软件,microsoft office哪个可以创建网页?
移民网站制作流程,怎么看加拿大移民官网?
建站之星代理平台如何选择最佳方案?
公司网站制作需要多少钱,找人做公司网站需要多少钱?
油猴 教程,油猴搜脚本为什么会网页无法显示?
长沙企业网站制作哪家好,长沙水业集团官方网站?
建站之星安装步骤有哪些常见问题?
高端网站建设与定制开发一站式解决方案 中企动力
贸易公司网站制作流程,出口贸易网站设计怎么做?
c# Task.Yield 的作用是什么 它和Task.Delay(1)有区别吗
巅云智能建站系统:可视化拖拽+多端适配+免费模板一键生成
广州网站制作公司哪家好一点,广州欧莱雅百库网络科技有限公司官网?
大连网站制作费用,大连新青年网站,五年四班里的视频怎样下载啊?
如何在服务器上三步完成建站并提升流量?
详解免费开源的.NET多类型文件解压缩组件SharpZipLib(.NET组件介绍之七)
香港服务器网站生成指南:免费资源整合与高速稳定配置方案
洛阳网站制作公司有哪些,洛阳的招聘网站都有哪些?
c# 在高并发下使用反射发射(Reflection.Emit)的性能
宠物网站制作html代码,有没有专门介绍宠物如何养的网站啊?
如何用wdcp快速搭建高效网站?
网站规划与制作是什么,电子商务网站系统规划的内容及步骤是什么?
企业宣传片制作网站有哪些,传媒公司怎么找企业宣传片项目?
建站之星如何快速解决建站难题?
*请认真填写需求信息,我们会在24小时内与您取得联系。