Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 如何在不失去迭代器优点的情况下重载迭代器函数_.net_Vb.net_Yield Return - Fatal编程技术网

.net 如何在不失去迭代器优点的情况下重载迭代器函数

.net 如何在不失去迭代器优点的情况下重载迭代器函数,.net,vb.net,yield-return,.net,Vb.net,Yield Return,由于我通常使用VB.net作为我的首选语言,所以我还没有处理yielding。现在我读到,他们也在VB.net中引入了yielding,所以我试图了解它,现在我有一个问题 假设我有一个迭代器函数,它使用yielding。为了这个问题,我创建了一个相当无用的函数: Public Iterator Function Test(ByVal gap As Integer) As IEnumerable(Of Integer) Dim running As Integer Do Whil

由于我通常使用VB.net作为我的首选语言,所以我还没有处理
yield
ing。现在我读到,他们也在VB.net中引入了
yield
ing,所以我试图了解它,现在我有一个问题

假设我有一个
迭代器
函数,它使用
yield
ing。为了这个问题,我创建了一个相当无用的函数:

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
Public Function Test() As IEnumerable(Of Integer)
    Return Test(1)
End Function
它不再是一个迭代器函数了,所以我是否失去了只需要和需要数字一样多的时间的优势

它不再是迭代器函数了,所以我是否失去了只需要和需要数字一样多的时间的优势

你没有。迭代器函数并不神奇,它们所做的只是为您提供了一种实现
IEnumerable(of T)
接口的方便方法。因此,为了获得只生成所需值的优势,您只需要一个返回该接口的良好实现的方法。这可能是以下任何一种情况:

  • 迭代器方法,如
    测试(ByVal gap为整数)
  • 调用迭代器方法并返回其生成的对象的方法,如
    Test()
  • 一种方法,返回手动实现
    IEnumerable(of T)
    接口的类型的实例

感谢您的澄清。