Core源码(四)IEnumerable
首先我们去core的源码中去找IEnumerable发现并没有,如下

Core中应该是直接使用.net中对IEnumerable的定义

自己实现迭代器
迭代器是通过IEnumerable和IEnumerator接口来实现的,今天我们也来尝试实现自己的迭代器。
首先来看看这两个接口:
internal interface IEnumerable
{
[DispId(-)]
System.Collections.IEnumerator GetEnumerator();
}
public interface IEnumerator
{
object Current { get; }
bool MoveNext();
void Reset();
}
并没有想象的那么复杂。其中IEnumerable只有一个返回IEnumerator的GetEnumerator方法。而IEnumerator中有两个方法加一个属性。
接下来,我们继承IEnumerable接口并实现:
public class MyIEnumerable : IEnumerable
{
private string[] strList;
public MyIEnumerable(string[] strList)
{
this.strList=strList;
}
public IEnumerator GetEnumerator()
{
return new MyIEnumerator(strList);
}
}
public class MyIEnumerator:IEnumerator
{
private string[] strList;
private int position;
public MyIEnumerator(string[] strList)
{
this.strList=strList;
position=-;
}
public object Current
{
get{ return strList[position];}
}
public bool MoveNext()
{
position++;
if (position<strList.Length)
{
return true;
}
return false;
}
public void Reset()
{
position=-;
}
}
下面使用原始的方式调用:
static void Main(string[] args)
{
string[] strList=new string[]{"",""};
MyIEnumerable my =new MyIEnumerable(strList);
var enumerator=my.GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
//enumerator.Current=""; 这会报错
}
Console.WriteLine("-------------------------------");
foreach (var item in my)
{
Console.WriteLine(item);
}
}
这两种取值方式基本等效,因为实际clr编译后生成的代码是相同的。

由此可见,两者有这么个关系:

我们可以回答一个问题了“为什么在foreach中不能修改item的值?”:

我们还记得IEnumerator的定义吗,接口的定义就只有get没有set。所以我们在foreach中不能修改item的值。
yield的使用
你肯定发现了我们自己去实现IEnumerator接口还是有些许麻烦,并且上面的代码肯定是不够健壮。对的,.net给我们提供了更好的方式。
public IEnumerator GetEnumerator()
{
//return new MyIEnumerator(strList);
for (int i = ; i < strList.Length; i++)
{
yield return strList[i];
}
}
你会发现我们连MyIEnumerator都没要了,也可以正常运行。太神奇了。yield到底为我们做了什么呢?

好家伙,我们之前写的那一大坨。你一个yield关键字就搞定了。最妙的是这块代码:

这就是所谓的状态机吧!
我们调用GetEnumerator的时候,看似里面for循环了一次,其实这个时候没有做任何操作。只有调用MoveNext的时候才会对应调用for循环。
为什么Linq to Object中要返回IEnumerable?
因为IEnumerable是延迟加载的,每次访问的时候才取值。也就是我们在Lambda里面写的where、select并没有循环遍历(只是在组装条件),只有在ToList或foreache的时候才真正去集合取值了。这样大大提高了性能。
自己实现MyWhere:
public class MyIEnumerable : IEnumerable
{
private string[] strList;
public MyIEnumerable(string[] strList)
{
this.strList=strList;
}
public IEnumerator GetEnumerator()
{
//return new MyIEnumerator(strList);
for (int i = ; i < strList.Length; i++)
{
yield return strList[i];
}
}
public IEnumerable<string> MyWhere(Func<string,bool> func)
{
foreach (string item in this)
{
if (func(item))
{
yield return item;
}
}
}
}
FirstOrDefault的实现
内部调用了TryGetFirst。

private static TSource TryGetFirst<TSource>(this IEnumerable<TSource> source, out bool found)
{
if (source == null)
{
throw Error.ArgumentNull(nameof(source));
} if (source is IPartition<TSource> partition)
{
return partition.TryGetFirst(out found);
} if (source is IList<TSource> list)
{
if (list.Count > )
{
found = true;
return list[];
}
}
else
{
using (IEnumerator<TSource> e = source.GetEnumerator())
{
//同样调用了MoveNext方法
if (e.MoveNext())
{
found = true;
//Current属性在我们的自定义实现里面也有出现
return e.Current;
}
}
} found = false;
return default(TSource);
}
不传入筛选的实现
private static TSource TryGetFirst<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, out bool found)
{
if (source == null)
{
throw Error.ArgumentNull(nameof(source));
} if (predicate == null)
{
throw Error.ArgumentNull(nameof(predicate));
} if (source is OrderedEnumerable<TSource> ordered)
{
return ordered.TryGetFirst(predicate, out found);
} foreach (TSource element in source)
{
//循环,直接返回第一个符合条件的对象
if (predicate(element))
{
found = true;
return element;
}
} found = false;
return default(TSource);
}
传入筛选的实现
源码地址
https://gitee.com/qixinbo/MyKestrelServer/tree/master/DataStruct/EnumerableStudy
本文参考《农码一生》
https://www.cnblogs.com/zhaopei/p/5769782.html
Core源码(四)IEnumerable的更多相关文章
- 一个由正则表达式引发的血案 vs2017使用rdlc实现批量打印 vs2017使用rdlc [asp.net core 源码分析] 01 - Session SignalR sql for xml path用法 MemCahe C# 操作Excel图形——绘制、读取、隐藏、删除图形 IOC,DIP,DI,IoC容器
1. 血案由来 近期我在为Lazada卖家中心做一个自助注册的项目,其中的shop name校验规则较为复杂,要求:1. 英文字母大小写2. 数字3. 越南文4. 一些特殊字符,如“&”,“- ...
- 一起来看CORE源码(一) ConcurrentDictionary
先贴源码地址 https://github.com/dotnet/corefx/blob/master/src/System.Collections.Concurrent/src/System/Col ...
- ASP.NET Core[源码分析篇] - WebHost
_configureServicesDelegates的承接 在[ASP.NET Core[源码分析篇] - Startup]这篇文章中,我们得知了目前为止(UseStartup),所有的动作都是在_ ...
- ASP.NET Core[源码分析篇] - Authentication认证
原文:ASP.NET Core[源码分析篇] - Authentication认证 追本溯源,从使用开始 首先看一下我们通常是如何使用微软自带的认证,一般在Startup里面配置我们所需的依赖认证服务 ...
- DOTNET CORE源码分析之IOC容器结果获取内容补充
补充一下ServiceProvider的内容 可能上一篇文章DOTNET CORE源码分析之IServiceProvider.ServiceProvider.IServiceProviderEngin ...
- ASP.NET Core源码学习(一)Hosting
ASP.NET Core源码的学习,我们从Hosting开始, Hosting的GitHub地址为:https://github.com/aspnet/Hosting.git 朋友们可以从以上链接克隆 ...
- asp.net core源码地址
https://github.com/dotnet/corefx 这个是.net core的 开源项目地址 https://github.com/aspnet 这个下面是asp.net core 框架 ...
- ASP .NET CORE 源码地址
ASP .NET CORE 源码地址:https://github.com/dotnet/ 下拉可以查找相应的源码信息, 例如:查找 ASP .NET CORE Microsoft.Extension ...
- .net core 源码解析-web app是如何启动并接收处理请求
最近.net core 1.1也发布了,蹒跚学步的小孩又长高了一些,园子里大家也都非常积极的在学习,闲来无事,扒拔源码,涨涨见识. 先来见识一下web站点是如何启动的,如何接受请求,.net core ...
随机推荐
- Redux Class(immutable Record)引入的必要性 && Navigation引入方式
我的意见 和大家讨论一下几个问题 1. 项目里面没有用class规定的请求数据结构,调试数据的时候无法从前端获取请求的数据格式,要看后端接口,增加了调试的难度.我们以前会用immutable Reco ...
- docker 指定版本rpm包安装
1.docker rpm包下载地址 # https://download.docker.com/linux/centos/7/x86_64/stable/Packages/ 2.下载rpm包 # wg ...
- Java学习笔记之面向对象、static关键字
一周Java学习总结 今天就总结理清一下关于面向对象和面向过程的程序设计的一些不同特点,以及讲下static关键字. 面向对象 现在接触的Java是面向对象的,现在的程序开发几乎都是以面向对象为基础的 ...
- python Windows环境下文件路径问题
转自:http://blog.sina.com.cn/s/blog_5ee7254801013zu7.html 在python程序里面我们经常需要对文件进行操作,Windows下的文件目录路径使用反斜 ...
- 在python函数中默认参数的一些坑
一.默认参数 python为了简化函数的调用,提供了默认参数机制: 这样在调用pow函数时,就可以省略最后一个参数不写: 在定义有默认参数的函数时,需要注意以下: 必选参数必须在前面,默认参数在后: ...
- 1-5-JS基础-数组应用及实例应用
array 数组 一般简写arr 格式 var arr [ '第1个','第2个','第3个','第4个' ] 最后一个不要叫逗号 alert(arr.length) 弹出数组长度 4个 alert( ...
- linux学习(三)输入输出重定向和管道功能、cat命令、more命令
目录 输入输出重定向 输出重定向 管道功能 cat命令 more命令 @(输入输出重定向和管道功能) 输入输出重定向 输入重定向可以让用户将某个文件作为输入设备,输出重定向可以把某个文件作为输出设备, ...
- 【入门级】Docker基础介绍(一)
Docker发展 Docker目前有两个版本: 1.Docker EE:企业版 2.Docker CE:社区版 Open Container Initiative倡议,包含两个规范, 1.运行时规范: ...
- Druid-代码段-2-1
所属文章:池化技术(一)Druid是如何管理数据库连接的? 本代码段对应主流程2,具体用来初始化整个连接池: public void init() throws SQLException { if ( ...
- Python爬虫(requests模块)
Requests是唯一的一个非转基因的Python HTTP库,人类可以安全享用. Requests基础学习 使用方法: 1.导入Requests模块: import requests 2.尝试用g ...