如何在不失去迭代器优点的情况下重载迭代器函数
How to overload an iterator function without losing the advantages of the iterator
因为我通常使用 VB.net 作为我选择的语言,所以我还没有应付 yield
ing。现在我读到,他们也向 VB.net 介绍了 yield
ing,所以我试图了解它,现在我有一个问题。
假设我有一个使用 yield
ing 的 Iterator
函数。为了这个问题,我创建了这个相当无用的函数:
Public Iterator Function Test(ByVal gap As Integer) As IEnumerable(Of Integer)
Dim running As Integer
Do While running < (Integer.MaxValue - gap)
Yield running
running += gap
Loop
End Function
如果我理解 yield
ing 正确,那么代码会在 yield
ing 之后停止,并且只会在要求下一个项目时继续。
所以,在我的示例中...如果获取 running
变量的下一个值需要 1 秒,那么如果我只需要第一个数字,我的代码将只需要 运行 1 秒如果我需要 5 个数字,它会 运行 5 秒。
到目前为止一切顺利,但现在我想重载我的函数:
Public Function Test() As IEnumerable(Of Integer)
Return Test(1)
End Function
它不再是一个 Iterator
函数,所以我是否失去了只需要与我需要数字一样多的时间的优势?
It's not an Iterator function anymore, so did I lose the advantage of only needing as much time as I need numbers?
你没有。迭代器函数并不神奇,它们所做的只是为您提供一种实现 IEnumerable(Of T)
接口的便捷方式。因此,为了获得仅生成所需值的优势,您所需要的只是一个 returns 该接口的良好实现的方法。这可能是以下任何一个:
- 一个迭代器方法,就像你的
Test(ByVal gap As Integer)
。
- 一种调用迭代器方法和 returns 它产生的对象的方法,例如您的
Test()
.
- 一种 returns 手动实现
IEnumerable(Of T)
接口的类型实例的方法。
因为我通常使用 VB.net 作为我选择的语言,所以我还没有应付 yield
ing。现在我读到,他们也向 VB.net 介绍了 yield
ing,所以我试图了解它,现在我有一个问题。
假设我有一个使用 yield
ing 的 Iterator
函数。为了这个问题,我创建了这个相当无用的函数:
Public Iterator Function Test(ByVal gap As Integer) As IEnumerable(Of Integer)
Dim running As Integer
Do While running < (Integer.MaxValue - gap)
Yield running
running += gap
Loop
End Function
如果我理解 yield
ing 正确,那么代码会在 yield
ing 之后停止,并且只会在要求下一个项目时继续。
所以,在我的示例中...如果获取 running
变量的下一个值需要 1 秒,那么如果我只需要第一个数字,我的代码将只需要 运行 1 秒如果我需要 5 个数字,它会 运行 5 秒。
到目前为止一切顺利,但现在我想重载我的函数:
Public Function Test() As IEnumerable(Of Integer)
Return Test(1)
End Function
它不再是一个 Iterator
函数,所以我是否失去了只需要与我需要数字一样多的时间的优势?
It's not an Iterator function anymore, so did I lose the advantage of only needing as much time as I need numbers?
你没有。迭代器函数并不神奇,它们所做的只是为您提供一种实现 IEnumerable(Of T)
接口的便捷方式。因此,为了获得仅生成所需值的优势,您所需要的只是一个 returns 该接口的良好实现的方法。这可能是以下任何一个:
- 一个迭代器方法,就像你的
Test(ByVal gap As Integer)
。 - 一种调用迭代器方法和 returns 它产生的对象的方法,例如您的
Test()
. - 一种 returns 手动实现
IEnumerable(Of T)
接口的类型实例的方法。