枚举器和迭代器
相关知识
官方
IEnumerable<T> 接口:https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.ienumerable-1?view=net-5.0
IEnumerator<T> 接口:https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.ienumerator-1?view=net-5.0
迭代器:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/iterators
本地函数和异常(注:用本地函数解决迭代块延迟执行的问题):https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/local-functions#local-functions-and-exceptions
其它
IEnumerable(注:这个写的挺好的):https://blog.youkuaiyun.com/weixin_42339460/article/details/80733758
C#迭代器原理详解:https://blog.youkuaiyun.com/qq_36576410/article/details/86690605
相关书籍:
《C#图解教程(第4版)》
第18章:枚举器和迭代器
《C#高级编程(第11版)》
第7章 7.8小节: 枚举
注意事项
1. 实现IEnumerable接口的类型叫可枚举类型,实现IEnumerator接口的叫枚举器,包含yield语句的方法或属性叫迭代器块,迭代器块必须声明为返回IEnumerator或IEnumerable接口,或者这些接口的泛型版本。这个块可以包含多条yield return语句或yield break语句,但不能包含return语句。
2. 使用迭代器块,编译器会生成一个枚举器,迭代器块中的代码会被封装到这个枚举器的MoveNext方法中,然后返回这个枚举器,所以只有调用枚举器的MoveNext方法时,迭代器块中的代码才会执行,这就叫延迟执行。
3. 可以使用本地函数解决延迟执行引起的一些问题。