C#foreach原理
本文主要记录我在学习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 = ; 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 = -; public PeopleEnum(Person[] list)
{
_people = list;
} public bool MoveNext()
{
position++;
return (position < _people.Length);
} public void Reset()
{
position = -;
} 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[]
{
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 = ; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
} // Implementation for the GetEnumerator method.
IEnumerator IEnumerable.GetEnumerator()
{
for (int i = ; i < _people.Length; i++)
{
yield return _people[i];
}
} } class App
{
static void Main()
{
Person[] peopleArray = new Person[]
{
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);
}
}

yield和return一起使用才有意义,这个关键字就是为迭代器服务的,所以有yield所在的方法是迭代器,作用是返回相同类型的值的一个序列,执行到yield return 这个语句之后,函数并不直接返回,而是保存此元素到序列中,继续执行,直到函数体结束或者yield break。
但是生成的此迭代器的函数体并不会在直接调用时运行,只会在foreach中迭代时执行。如:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection; // 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
{
private Person[] _people; public People(Person[] pArray)
{
_people = new Person[pArray.Length]; for (int i = ; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
} // Implementation for the GetEnumerator method.
public IEnumerable GetMyEnumerator()
{
Console.WriteLine("a");
for (int i = ; i < _people.Length; i++)
{
Console.WriteLine(i.ToString());
yield return _people[i];
}
} } class App
{
static void Main()
{
Person[] peopleArray = new Person[]
{
new Person("John", "Smith"),
new Person("Jim", "Johnson"),
new Person("Sue", "Rabon"),
}; People peopleList = new People(peopleArray);
IEnumerable myEnumerator = peopleList.GetMyEnumerator();
Console.WriteLine("Start Iterate");
foreach (Person p in myEnumerator)
{
Console.WriteLine(p.firstName + " " + p.lastName);
} Console.ReadLine();
}
}

结果:

转载:https://www.cnblogs.com/alongdada/p/7598119.html
C#foreach原理的更多相关文章
- Foreach原理
本质:实现了一个IEnumerable接口, 01.为什么数组和集合可以使用foreach遍历? 解析:因为数组和集合都实现了IEnumerable接口,该接口中只有一个方法,GetEnumerato ...
- .net学习之集合、foreach原理、Hashtable、Path类、File类、Directory类、文件流FileStream类、压缩流GZipStream、拷贝大文件、序列化和反序列化
1.集合(1)ArrayList内部存储数据的是一个object数组,创建这个类的对象的时候,这个对象里的数组的长度为0(2)调用Add方法加元素的时候,如果第一次增加元神,就会将数组的长度变为4往里 ...
- Array.forEach原理,仿造一个类似功能
Array.forEach原理,仿造一个类似功能 array.forEach // 设一个arr数组 let arr = [12,45,78,165,68,124]; let sum = 0; // ...
- 浅析foreach原理
在日常开发工作中,我们发现很多对象都能通过foreach来遍历,比如HashTable.Dictionary.数组等数据类型.那为何这些对象能通过foreach来遍历呢?如果写一个普通的Person类 ...
- C#学习笔记:foreach原理
这篇随笔是对上一篇随笔C#关键字:yield的扩展. 关于foreach 首先,对于 foreach ,大家应该都非常熟悉,这里就简单的描述下. foreach 语句用于对实现 System.Col ...
- Foreach 原理
public class Person { private string[] friends = { "asf", "ewrqwe", "ddd&qu ...
- C# foreach 原理以及模拟的实现
public class Person:IEnumerable //定义一个person类 并且 实现IEnumerable 接口 (或者不用实现此接口 直接在类 //里面写个GetEnu ...
- 涉及 C#的 foreach问题
当时是用foreach实现遍历,但是函数传入参数是Object类型的,由于Objectl类型没有实现相关接口,所以foreach并不能执行. 那么下面我们来看看,想要使用foreach需要具备什么条件 ...
- mybatis foreach 循环 list(map)
直接上代码: 整体需求就是: 1.分页对象里面有map map里面又有数组对象 2.分页对象里面有list list里面有map map里面有数组对象. public class Page { pri ...
随机推荐
- kvm的命令简单使用
virsh命令常用参数总结 参数 参数说明 基础操作 list 查看虚拟机列表,列出域 start 启动虚拟机,开始一个(以前定义的)非活跃的域 shutdown 关闭虚拟机,关闭一个域 dest ...
- Redis集群方式
Redis有三种集群方式:主从复制,哨兵模式和集群. 1.主从复制 主从复制原理: 从服务器连接主服务器,发送SYNC命令: 主服务器接收到SYNC命名后,开始执行BGSAVE命令生成RDB文件并使用 ...
- .Net Core WebAPI + Axios +Vue 实现下载与下载进度条
故事的开始 老板说:系统很慢,下载半个小时无法下载,是否考虑先压缩再给用户下载? 本来是已经压缩过了,不过第一反应应该是用户下的数量多,导致压缩包很大,然后自己测试发现,只是等待的时间比较久而已,仍然 ...
- 使用PD(Power Designer)设计数据库,并且生成可执行的SQL文件创建数据库(本文以SQL Server Management Studio软件执行为例)
下载和安装PD: 分享我的软件资源,里面包含了对PD汉化包(链接出问题时可以留言,汉化包只能对软件里面部分菜单栏汉化) 链接:https://pan.baidu.com/s/1lNt1UGZhtDV8 ...
- tp5的 LayUI分页样式实现
1.先配置你的分页参数: //分页配置 'paginate' => [ 'type' => 'Layui', 'var_page' => 'page', 'li ...
- Redis系列(三):redisServer、redisDb、redisObject、sds四大结构体理解
一.源码下载: Windows中的Redis源码下载:https://github.com/microsoftarchive/redis/tree/3.2 根据官网说明可知,用VS2013编译,但是必 ...
- PyQt中QThread多线程的正确用法【待完善】
先贴几篇有意思的讨论 https://www.qt.io/blog/2010/06/17/youre-doing-it-wrong#commento-login-box-container https ...
- GitHub 热点速览 Vol.24:程序员自我增值,优雅赚零花钱
摘要:升职加薪,出任 CTO,迎娶白富美/高帅富,走向人生巅峰是很多人的梦想.在本期的热点速览中你将了解自由作者 Easy 如何优雅赚取零花钱的方法,以及定投改变命运 -- 让时间陪你慢慢变富.说到程 ...
- 单例模式的DCL方式,您不可不知道的知识点
单例模式的DCL是一种比较好的单例实现方式,面试中被问及的频率非常高,考察的方式也多种多样.这里简单整理了一下,这里面的每一个点最好都能够做到烂熟于心: 1 public class Test { 2 ...
- 东方步进电机马达驱动板CVK系列说明书
东方步进电机马达驱动板CVK系列说明书