首先我们去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的更多相关文章

  1. 一个由正则表达式引发的血案 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. 一些特殊字符,如“&”,“- ...

  2. 一起来看CORE源码(一) ConcurrentDictionary

    先贴源码地址 https://github.com/dotnet/corefx/blob/master/src/System.Collections.Concurrent/src/System/Col ...

  3. ASP.NET Core[源码分析篇] - WebHost

    _configureServicesDelegates的承接 在[ASP.NET Core[源码分析篇] - Startup]这篇文章中,我们得知了目前为止(UseStartup),所有的动作都是在_ ...

  4. ASP.NET Core[源码分析篇] - Authentication认证

    原文:ASP.NET Core[源码分析篇] - Authentication认证 追本溯源,从使用开始 首先看一下我们通常是如何使用微软自带的认证,一般在Startup里面配置我们所需的依赖认证服务 ...

  5. DOTNET CORE源码分析之IOC容器结果获取内容补充

    补充一下ServiceProvider的内容 可能上一篇文章DOTNET CORE源码分析之IServiceProvider.ServiceProvider.IServiceProviderEngin ...

  6. ASP.NET Core源码学习(一)Hosting

    ASP.NET Core源码的学习,我们从Hosting开始, Hosting的GitHub地址为:https://github.com/aspnet/Hosting.git 朋友们可以从以上链接克隆 ...

  7. asp.net core源码地址

    https://github.com/dotnet/corefx 这个是.net core的 开源项目地址 https://github.com/aspnet 这个下面是asp.net core 框架 ...

  8. ASP .NET CORE 源码地址

    ASP .NET CORE 源码地址:https://github.com/dotnet/ 下拉可以查找相应的源码信息, 例如:查找 ASP .NET CORE Microsoft.Extension ...

  9. .net core 源码解析-web app是如何启动并接收处理请求

    最近.net core 1.1也发布了,蹒跚学步的小孩又长高了一些,园子里大家也都非常积极的在学习,闲来无事,扒拔源码,涨涨见识. 先来见识一下web站点是如何启动的,如何接受请求,.net core ...

随机推荐

  1. Python:将爬取的网页数据写入Excel文件中

    Python:将爬取的网页数据写入Excel文件中 通过网络爬虫爬取信息后,我们一般是将内容存入txt文件或者数据库中,也可以写入Excel文件中,这里介绍关于使用Excel文件保存爬取到的网页数据的 ...

  2. Python Django 支付宝 扫码支付

    安装python-alipay-sdk pip install python-alipay-sdk --upgradepip install crypto 如果是python 2.7安装0.6.4这个 ...

  3. nodejs攻略——第一章 配置

    nodejs这玩意吧,我也是心血来潮的学习,所以啊.看这篇文章之前请大家有以下技能,如果没有..我不确定你能看得懂,毕竟我文采水平实在有限. 前置技能要求: c#或java 熟练+ JavaScrip ...

  4. 【Linux命令】磁盘分区,格式化,挂载命令,创建交换分区(fdisk,mkfs,mount,umount)

    友情链接 磁盘分区,格式化,挂载,创建交换分区:https://www.cnblogs.com/HeiDi-BoKe/p/11936998.html RAID工作级别:https://www.cnbl ...

  5. iOS sqlite ORM框架-LKDBHelper

    LKDBHelper 一个sqlite ORM(全自动操作数据库)框架. 线程安全.不再担心递归锁死的问题 安装要求 iOS 4.3+ 仅支持 ARC FMDB 添加到你的项目 如果你使用 Cocoa ...

  6. 使用 TSPITR 恢复删除的表空间的步骤 (Doc ID 1277795.1)

    Steps To Recover A Dropped Tablespace Using TSPITR (Doc ID 1277795.1) APPLIES TO: Oracle Database - ...

  7. Php—使用phpMyAdmin报错

    1.Warning in ./libraries/config/FormDisplay.php#661  "continue" targeting switch is equiva ...

  8. centos图形化桌面安装过程

    连接 1.安装xwindow yum -y groupinstall "X Window System" \\安装 X Window System 环境 2.安装gnome des ...

  9. LRU hashMap(拉链) + 双向链表 java实现

    //基于 hash (拉链法) + 双向链表,LRUcache //若改为开放寻址,线性探测法能更好使用cpuCache public class LRU { private class Node { ...

  10. go语言设计模式之Concurrency workers pool

    worker.go package main import ( "fmt" "strings" ) type WorkerLauncher interface ...