IEnumerator vs Iterator
2021/12/1 6:06:06
本文主要是介绍IEnumerator vs Iterator,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
IEnumerator vs Iterator
IEnumerator
不考虑Reset
方法和原始列表的可变性,NoveNext
和Current
的只读向前用法:
Initially, the enumerator is positioned before the first element in the collection. You must call the MoveNext
method to advance the enumerator to the first element of the collection before reading the value of Current
; otherwise, Current
is undefined.
Current
returns the same object until MoveNext
is called. MoveNext
sets Current
to the next element.
If MoveNext
passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext
returns false. When the enumerator is at this position, subsequent calls to MoveNext
also return false. If the last call to MoveNext
returned false, Current
is undefined.
输入数据,并初始化枚举器:
let ls = [0;1;2] let enumerator = (Seq.ofList ls).GetEnumerator() let ls = []
此时调用Current
会抛出异常,印证第一段描述:
enumerator.Current //InvalidOperationException : 枚举尚未开始。请调用 MoveNext。
我们改正代码,连续运行,直到序列的末尾:
let ls = [0;1;2] let enumerator = (Seq.ofList ls).GetEnumerator() show <| enumerator.MoveNext() // true show enumerator.Current // 0 show <| enumerator.MoveNext() // true show enumerator.Current // 1 show <| enumerator.MoveNext() // true show enumerator.Current // 2
当再次调用MoveNext()
返回false,接上段代码:
show <| enumerator.MoveNext() // false
当MoveNext()
返回false之后,如果此时调用Current
会抛出异常:
show enumerator.Current // InvalidOperationException : 枚举已完成。
当MoveNext()
返回false之后,继续调用MoveNext()
不会抛出异常,它总是返回false:
show <| enumerator.MoveNext() // false show <| enumerator.MoveNext() // false show <| enumerator.MoveNext() // false show <| enumerator.MoveNext() // false
当输入序列为空时,行为如下:
let ls = [] let enumerator = (Seq.ofList ls).GetEnumerator() show <| enumerator.MoveNext() // false show enumerator.Current // InvalidOperationException : 枚举已完成。
Iterator
javaScript的枚举器用法如下:
const iterable = ['a', 'b']; const iterator = iterable[Symbol.iterator](); iterator.next() //, { value: 'a', done: false } iterator.next() //, { value: 'b', done: false } iterator.next() //, { value: undefined, done: true }
这篇关于IEnumerator vs Iterator的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南