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 ...
随机推荐
- SpringBoot+JWT+Shiro+MybatisPlus实现Restful快速开发后端脚手架
一.背景 前后端分离已经成为互联网项目开发标准,它会为以后的大型分布式架构打下基础.SpringBoot使编码配置部署都变得简单,越来越多的互联网公司已经选择SpringBoot作为微服务的入门级微框 ...
- appium元素定位之AndroidUiAutomator
UIAutomator 元素定位是 Android 系统原生支持的定位方式,虽然与 xpath 类似,但比它更好用,并且支持元素全部的属性定位,定位原理是通过 android 自带的android u ...
- URL跳转绕过姿势
POC "@" http://www.target.com/redirecturl=http://whitelist.com@evil.com "\" http ...
- 77777 77777(2) WriteUp 绕waf技巧学习
两个题的代码都是一样的 只是waf不一样 贴出代码 <?php function update_point($p,$point){ global $link; $q = sprintf(&quo ...
- Mybatis的逆向工程,自动生成代码(Mapper,xml,bean)
步骤: 1. 新建一个Maven项目: 然后导入maven依赖: <dependencies> <dependency> <groupId>org.mybatis& ...
- 23种设计模式之Builder设计模式
概述 建造者模式(Builder Pattern),是创造性模式之一,Builder 模式的目的则是为了将对象的构建与展示分离.Builder 模式是一步一步创建一个复杂对象的创建型模式,它允许用户在 ...
- 微信支付和微信支付通知基于sdk的说明(2)
前期准备工作 微信商户账户/密码(获取appid等信息) 微信公众号账户/密码(获取cert证书等信息,不做线上退款不需要证书) 下载php支付demo 从商户平台进入的话是以下界面或者直接搜索公众号 ...
- mssql 系统函数 字符串函数 space 功能简介
转自: http://www.maomao365.com/?p=4672 一.space 函数功能简介 space功能:返回指定数量的空格参数简介: 参数1: 指定数量,参数需为int类型 注意事项 ...
- [Linux] 安装grafana并且添加influxdb监控
安装grafana,官网提供了ubuntu的安装包,直接进行安装 wget https://dl.grafana.com/oss/release/grafana_6.5.1_amd64.deb dpk ...
- Linux系统学习 一、安装,调试
环境 主机: Windows 10 虚拟机: VMware 15 Pro 镜像: 一.安装过程: 然后开启虚拟机 设置主机名 时区 密码 最小安装 等着 重启 登录 二.配置静态IP地址 输入ifco ...