我们先思考几个问题:
1.为什么在foreach中不能修改item的值?(IEnumerator的Current为只读)
2.要实现foreach需要满足什么条件?(实现IEnumerator接口来实现的)
3.为什么Linq to Object中要返回IEnumerable?(因为IEnumerable是延迟加载的,每次访问的时候才取值。也就是我们在Lambda里面写的where、select并没有循环遍历(只是在组装条件),只有在ToList或foreache的时候才真正去集合取值了。这样大大提高了性能。)

.net中迭代器是通过IEnumerable和IEnumerator接口来实现的,今天我们也来依葫芦画瓢。

using System;
using System.Collections; namespace RedisTest
{
class Program
{
static void Main(string[] args)
{
string[] str = { "", "", "", "", "" };
var aaa = new MyIEnumerable(str);
var bbb = aaa.GetEnumerator();
while (bbb.MoveNext())
{
Console.WriteLine(bbb.Current);
}
Console.WriteLine("---------------------------------------------------------");
foreach (var item in aaa)
{
Console.WriteLine(item);
}
Console.Read();
/*
1111
2222
3333
4444
5555
---------------------------------------------------------
1111
2222
3333
4444
5555
*/
}
} public class MyIEnumerable : IEnumerable
{
private string[] strList;
public MyIEnumerable(string[] _strList)
{
strList = _strList;
}
public IEnumerator GetEnumerator()
{
return new MyIEnumerator(strList);
}
} public class MyIEnumerator : IEnumerator
{
private string[] strList;
private int position; public MyIEnumerator(string[] _strList)
{
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 = -;
}
}
}

yield的使用

using System;
using System.Collections; namespace RedisTest
{
class Program
{
static void Main(string[] args)
{
string[] str = { "", "", "", "", "" };
var aaa = new MyIEnumerable(str);
var bbb = aaa.GetEnumerator();
while (bbb.MoveNext())
{
Console.WriteLine(bbb.Current);
}
Console.WriteLine("---------------------------------------------------------");
foreach (var item in aaa)
{
Console.WriteLine(item);
}
Console.Read();
/*
1111
2222
3333
4444
5555
---------------------------------------------------------
1111
2222
3333
4444
5555
*/ }
} public class MyIEnumerable
{
private string[] strList;
public MyIEnumerable(string[] _strList)
{
strList = _strList;
}
public IEnumerator GetEnumerator()
{
for (int i = ; i < strList.Length; i++)
{
yield return strList[i];
}
}
} }

我们调用GetEnumerator的时候,看似里面for循环了一次,其实这个时候没有做任何操作。只有调用MoveNext的时候才会对应调用for循环:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq; namespace RedisTest
{
class Program
{
static void Main(string[] args)
{
string[] str = { "", "", "", "", "" };
var aaa = new MyIEnumerable(str);
var bbb = aaa.MyWhere(x => x != "");
var ccc = bbb.ToList();
//现在看到了吧。执行到MyWhere的时候什么动作都没有(返回的就是IEnumerable),只有执行到ToList的时候才代码才真正的去遍历筛选。
//这里的MyWhere其实可以用扩展方法来实现,提升逼格。(Linq的那些查询操作符就是以扩展的形式实现的)
Console.Read(); }
} public class MyIEnumerable
{
private string[] strList;
public MyIEnumerable(string[] _strList)
{
strList = _strList;
}
public IEnumerator GetEnumerator()
{
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;
}
}
}
} }

IEnumerable和IEnumerator接口的更多相关文章

  1. 细说 C# 中的 IEnumerable和IEnumerator接口

    我们先思考几个问题: 为什么在foreach中不能修改item的值? 要实现foreach需要满足什么条件? 为什么Linq to Object中要返回IEnumerable? 接下来,先开始我们的正 ...

  2. C# IEnumerable 和 IEnumerator接口浅析

    温故而知新,可以为师矣,有空经常复习一下基础知识是有必要的,并且能加深理解和记忆. Foreach常用于循环访问集合,对实现IEnumerable的接口的容器进行遍历,IEnumerable和IEnu ...

  3. IEnumerable、IEnumerator接口(如何增加迭代器功能)

    IEnumerable.IEnumerator接口封装了迭代器功能,有了它,我们不需要将内部集合暴露出去,外界只需要访问我的迭代器接口方法即可遍历数据. 在C#中,使用foreach语句来遍历集合.f ...

  4. 迭代器学习之一:使用IEnumerable和IEnumerator接口

    写博客是检验我学习的成果之一以及自我总结的一种方式,以后会经常利用这种方式进行技术交流和自我总结,其中认识不深难免会有错误,但是一直懂得不懂就问,不懂就学的道理! 1.首先看一个简单的列子 , , , ...

  5. C#基础知识系列九(对IEnumerable和IEnumerator接口的糊涂认识)

    前言 IEnumerable.IEnumerator到现在为止对这两个接口还是不太理解,不理解但是自己总是想着试着要搞明白,毕竟自己用的少,所以在此先记录一下.以备自己日后可以来翻查,同时也希望园子里 ...

  6. C# ~ 从 IEnumerable / IEnumerator 到 IEnumerable<T> / IEnumerator<T> 到 yield

    IEnumerable / IEnumerator 首先,IEnumerable / IEnumerator 接口定义如下: public interface IEnumerable /// 可枚举接 ...

  7. IEnumerable和IEnumerator

    概述 IEnumerable和IEnumerator接口存在的意义:用来实现迭代的功能! public interface IEnumerable { IEnumerator GetEnumerato ...

  8. IEnumerable和IEnumerator 详解 (转)

    原文链接:http://blog.csdn.net/byondocean/article/details/6871881 参考链接:http://www.cnblogs.com/hsapphire/a ...

  9. [转]那些年我还不懂:IList,ICollection,IEnumerable,IEnumerator,IQueryable

    1.首先看一个简单的例子 int[] myArray = { 1, 32, 43, 343 }; IEnumerator myie = myArray.GetEnumerator(); myie.Re ...

随机推荐

  1. 将文本(lrc,txt)文件转换成UTF-8格式

    UTF-8是UNICODE的一种变长字符编码又称万国码,由Ken Thompson于1992年创建.现在已经标准化为RFC 3629.UTF-8用1到6个字节编码UNICODE字符.用在网页上可以同一 ...

  2. html5 实时监听输入框值变化的完美方案:oninput & onpropertychange

    结合 HTML5 标准事件 oninput 和 IE 专属事件 onpropertychange 事件来监听输入框值变化. H5手机端: <input type="text" ...

  3. sqlite limit offset

    limit 0,20 表示从第1条开始取20条数据 limit 20 offset 2  表示从第2条开始取出20条数据

  4. split('\r\n')

    '\r'是回车,'\n'是换行,前者使光标到行首,后者使光标下移一格.通常用的Enter是两个加起来. 实际我的脚本读取FTP的列表,如果用的split("\r\n"),可以获得正 ...

  5. 使用block的时候,导致的内存泄漏

    明确,只要在block里边用到我们自己的东西,成员变量,self之类的,我们都需要将其拿出来,把它做成弱指针以便之后进行释放. 在ZPShareViewController这个控制器中,由如下代码: ...

  6. CMake 示例

    1.需求 [1].使用第三方动/静太库 [2].本身代码部分编译为动/静态库 [3]多项目管理 原文转自:http://blog.csdn.net/shuyong1999/article/detail ...

  7. 【转】Python中的运算符

    [转]Python中的运算符 说完常用的数据类型,再来说下运算符.运算符用于将各种类型的数据进行运算,让静态的数据跑起来. 编程语言中的运算大致分为以下几个大类: 算术运算, 用于加减乘除等数学运算 ...

  8. W-GAN系 (Wasserstein GAN、 Improved WGAN)

    学习总结于国立台湾大学 :李宏毅老师 WGAN前作:Towards Principled Methods for Training Generative Adversarial Networks  W ...

  9. ARMV8 datasheet学习笔记4:AArch64系统级体系结构之Self-hosted debug

    1. 前言 2. 关于self-hosted debug Debugger调试器 是操作系统或系统软件的一部分,它会处理debug exception或修改debug system register, ...

  10. python计算最大公约数和最小公倍数

    a=4 b=2 def gcd(a,b): return a if b==0 else gcd(b,a%b) def lcm(a,b): return a*b//gcd(a,b) print(gcd( ...