6.2 C# 2:利用 yield 语句简化迭代器
class Program
{
static void Main(string[] args)
{
object[] values = new object[] { "a", "b", "c", "d", "e" };
IterationSample sample = new IterationSample(values, );
foreach (var item in sample)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
public class IterationSample : IEnumerable
{
public object[] values;
int startPoint;
public IterationSample(object[] values, int startingPoint)
{
this.values = values;
this.startPoint = startingPoint;
}
public IEnumerator GetEnumerator()
{
//return new IterationSampleIterator(this);
for (int index = ; index < values.Length; index++)
{
yield return values[(index + startPoint) % values.Length];
}
}
}
public class IterationSampleIterator : IEnumerator
{
IterationSample parent;
int position;
public IterationSampleIterator(IterationSample parent)
{
this.parent = parent;
this.position = -;
}
public object Current
{
get
{
if (position == - || position == parent.values.Length)
{
throw new InvalidOperationException();
}
int index = position + parent.values.Length;
index = index % parent.values.Length;
return parent.values[index];
}
} public bool MoveNext()
{
if (position != parent.values.Length)
{
position++;
}
return position < parent.values.Length;
} public void Reset()
{
position = -;
}
}
6.2.2 观察迭代器的工作流程
class Program
{
static readonly string Padding = new string(' ', );
static void Main(string[] args)
{
IEnumerable<int> iterable = CreatteEnumerable(Padding);
IEnumerator<int> iterator = iterable.GetEnumerator();
Console.WriteLine("starting iterate"); while (true)
{
Console.WriteLine("=======================================");
Console.WriteLine("calling MoveNext()");
bool result = iterator.MoveNext();
Console.WriteLine("moveNext result = {0}", result);
if (!result)
break;
Console.WriteLine("fetching current");
Console.WriteLine("current result = {0}", iterator.Current);
} Console.ReadKey();
}
static IEnumerable<int> CreatteEnumerable(string Padding)
{
Console.WriteLine("{0} start of createEnumerbale padding", Padding); for (int i = ; i < ; i++)
{
Console.WriteLine("{0} about to yield {1}", Padding, i);
yield return i;
Console.WriteLine("{0} after padding", Padding);
}
Console.WriteLine("{0} yield final value ", Padding);
yield return -;
Console.WriteLine("{0} end of createEnumerable();", Padding);
}
/* starting iterate
=======================================
calling MoveNext()
start of createEnumerbale padding
about to yield 0
moveNext result = True
fetching current
current result = 0
=======================================
calling MoveNext()
after padding
about to yield 1
moveNext result = True
fetching current
current result = 1
=======================================
calling MoveNext()
after padding
about to yield 2
moveNext result = True
fetching current
current result = 2
=======================================
calling MoveNext()
after padding
yield final value
moveNext result = True
fetching current
current result = -1
=======================================
calling MoveNext()
end of createEnumerable();
moveNext result = False */
}
6.2.3 进一步了解迭代器执行流程
1. 使用 yield break 结束迭代器的执行
class Program
{
static void Main(string[] args)
{
DateTime stop = DateTime.Now.AddSeconds();
foreach (var item in CountWithTimeLimit(stop))
{
Console.WriteLine("received {0}", item);
Thread.Sleep();
}
Console.ReadKey();
}
static IEnumerable<int> CountWithTimeLimit(DateTime limit)
{
for (int i = ; i < ; i++)
{
if (DateTime.Now >= limit)
{
yield break;
}
yield return i;
}
}
}
2. finally 代码块的执行
class Program
{
static void Main(string[] args)
{
DateTime stop = DateTime.Now.AddSeconds();
foreach (var item in CountWithTimeLimit(stop))
{
Console.WriteLine("received {0}", item);
if (item > )
{
Console.WriteLine("returning");
return;
}
Thread.Sleep();
}
Console.ReadKey();
}
static IEnumerable<int> CountWithTimeLimit(DateTime limit)
{
try
{
for (int i = ; i < ; i++)
{
if (DateTime.Now >= limit)
{
yield break;
}
yield return i;
}
}
finally
{
Console.WriteLine("stopping");
Console.ReadKey();
}
}
/*
received 0
received 1
received 2
received 3
received 4
returning
stopping
*/
}
foreach 会在它自己的 finally 代码块中调用 IEnumerator 所提供的Dispose 方法(就像 using 语句)。
当迭代器完成迭代之前,你如果调用由迭代器代码块创建的迭代器上的 Dispose ,
那么状态机就会执行在代码当前“暂停”位置范围内的任何 finally 代码块。
这个解释复杂且有点详细,但结果却很容易描述:只要调用者使用了 foreach 循环,迭代器块中的 finally 将按照你期望的方式工作。
class Program
{
static void Main(string[] args)
{
DateTime stop = DateTime.Now.AddSeconds();
IEnumerable<int> iterable = CountWithTimeLimit(stop);
IEnumerator<int> iterator = iterable.GetEnumerator(); iterator.MoveNext();
Console.WriteLine("received {0}", iterator.Current); iterator.MoveNext();
Console.WriteLine("received {0}", iterator.Current); Console.ReadKey();
}
static IEnumerable<int> CountWithTimeLimit(DateTime limit)
{
try
{
for (int i = ; i < ; i++)
{
if (DateTime.Now >= limit)
{
yield break;
}
yield return i;
}
}
finally
{
Console.WriteLine("stopping");
Console.ReadKey();
}
}
/*
received 0
received 1
*/
}
幸好,作为开发人员我们不需要太关心编译器是如何解决这些问题的。不过,关于实现中的以下一些奇特之处还是值得了解的:
在第一次调用 MoveNext 之前, Current 属性总是返回迭代器产生类型的默认值;
在 MoveNext 返回 false 之后, Current 属性总是返回最后的生成值;
Reset 总是抛出异常,而不像我们手动实现的重置过程那样,为了遵循语言规范,这是必要的行为;
嵌套类总是实现 IEnumerator 的泛型形式和非泛型形式(提供给泛型和非泛型的IEnumerable 所用)。
6.3.2 迭代文件中的行
class Program
{
static void Main(string[] args)
{
string fileName = string.Format(@"{0}aaa.txt", AppDomain.CurrentDomain.BaseDirectory);
foreach (var item in ReadLines(fileName))
{
Console.WriteLine(item);
} Console.ReadKey();
}
static IEnumerable<string> ReadLines(string fileName)
{
using (TextReader reader = File.OpenText(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
}
6.3.3 使用迭代器块和谓词对项进行延迟过滤
class Program
{
static void Main(string[] args)
{
string fileName = string.Format(@"{0}aaa.txt", AppDomain.CurrentDomain.BaseDirectory); IEnumerable<string> lines = ReadLines(fileName);
Predicate<string> predicate = line => line.StartsWith("using"); foreach (var item in Where(lines, predicate))
{
Console.WriteLine(item);
} Console.ReadKey();
}
public static IEnumerable<T> Where<T>(IEnumerable<T> source, Predicate<T> predicate)
{
if (source.IsNull() || predicate.IsNull())
throw new ArgumentException(); return WhereImpl(source, predicate);
}
private static IEnumerable<T> WhereImpl<T>(IEnumerable<T> source, Predicate<T> predicate)
{
foreach (T item in source)
{
if (predicate(item))
{
yield return item;
}
}
}
static IEnumerable<string> ReadLines(string fileName)
{
return ReadLines(() => { return File.OpenText(fileName); });
}
static IEnumerable<string> ReadLines(Func<TextReader> provider)
{
using (TextReader reader = provider())
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
}
6.2 C# 2:利用 yield 语句简化迭代器的更多相关文章
- Python生成器以及yield语句
生成器是一种暂缓求值的技术,它可以用来生成一系列的值,但不会一次性生成所有的值,而只在需要的时候才计算和生成一个值. 通过yield语句构建生成器 要得到一个生成器,我们需要定义一个函数,这个函数返回 ...
- Python with yield语句
1.with 语句 语法: with expression as variable 需要引入一个上下文管理协议,实现的方法是为一个类定义 __enter__() 和 __exit__() 方法, 在执 ...
- 机器学习实战 - 读书笔记(13) - 利用PCA来简化数据
前言 最近在看Peter Harrington写的"机器学习实战",这是我的学习心得,这次是第13章 - 利用PCA来简化数据. 这里介绍,机器学习中的降维技术,可简化样品数据. ...
- javascript笔记04:let语句 和 yield语句 和 with语句
1.yield语句: <script type="application/javascript; version=1.7"> function generator() ...
- 利用switch语句计算特定的年份的月份共有几天。
//利用switch语句计算特定的年份的月份共有几天. let year =2015 let month =2 //先判断闰年中二月份的情况 ifmonth ==2 { if (year %400 = ...
- yield语句
自C#的第一个版本以来,使用foreach语句可以轻松地迭代集合.在C#1.0中,创建枚举器仍需要做大量的工作.C#2.0添加了yield语句,以便于创建枚举器.yield return语句返 ...
- 【机器学习实战】第13章 利用 PCA 来简化数据
第13章 利用 PCA 来简化数据 降维技术 场景 我们正通过电视观看体育比赛,在电视的显示器上有一个球. 显示器大概包含了100万像素点,而球则可能是由较少的像素点组成,例如说一千个像素点. 人们实 ...
- 利用while语句,条件为输入的字符不为'\n'.
题目:输入一行字符,分别统计出其中英文字母.空格.数字和其它字符的个数. 1.程序分析:利用while语句,条件为输入的字符不为'\n'. 一个很简单的问题,其实换种方式就能完成,但是我就想怎么着才能 ...
- 生成器以及yield语句
生成器以及yield语句最初的引入是为了让程序员可以更简单的编写用来产生值的序列的代码. 以前,要实现类似随机数生成器的东西,需要实现一个类或者一个模块,在生成数据的同时 保持对每次调用之间状态的跟踪 ...
随机推荐
- 开启IIS的动态gzip功能
首先安装IIS的动态压缩模块 然后打开system32/intesrv下的applicationhost文件,找到其中的webServer节点,将其中的压缩配置部分替换如下: <?xml ver ...
- Clojure:将两个list合并成一个map
假设我们有两个list,分别是: (def a [“one” “two” “three”]) (def b [1 2 3]) 我们要把它们合为一个键值对应的map,做法很简单: 1. 先将a和b合为一 ...
- [ javascript ] getElementsByClassName与className和getAttribute!
对于javascript中的getElementsByClassName 在IE 6/7/8 不支持问题. 那么须要模拟出getElementsByClassName 须要採用className属性 ...
- 新手玩个人server(阿里云)
阿里云如火如荼的0元活动,事实上一開始我仅仅是去直播吧看阿森纳vs贝西克塔斯.姑且算是一种乱入,url这样的奇妙的东西应该是万维网的最真实的写照.当然那是上周第一会回合的事了.可是故事却如此的类似.并 ...
- 查找存在某字符的文件列表,不包括svn文件
find . ! -wholename '*.svn*' -print | xargs grep "img" | awk -F ':.' '{print $1}' | uniq
- Cocos2d-X开发中国象棋《三》開始场景的实现
在前面两节(第一节.第二节)中介绍了中国象棋的功能和project文件.在这篇博客中将介绍中国象棋的開始场景的实现 在写代码前先理清一下实现開始场景的思路: 1.打开游戏后进入開始场景,场景上显示一个 ...
- Spring+Mybatis之注册功能demo
这次先注册功能的是基于登录之后,所以很多配置,实体类等就不再赘述了. 首先也不是直接在地址栏输入一个网页就可以到注册页面的.而是需要通过后台发送一个请求从而跳转到注册页面 先写注册页面,body部分 ...
- write data to xml
public class Student { public int Id { get; set; } public string FirstName { get; set; } public stri ...
- Webstorm配置运行React Native
Webstorm配置运行React Native 1.选择配置 2.选择npm,设置package等参数 3.添加拓展工具 4.配置拓展工具(核心啊) 5.运行测试,ok的.
- 协同过滤算法中皮尔逊相关系数的计算 C++
template <class T1, class T2>double Pearson(std::vector<T1> &inst1, std::vector<T ...