在.NET 4.0中的迭代器等效物

huangapple go评论62阅读模式
英文:

Iterator equivalent in .net 4.0

问题

这段代码使用了在较新版本的.NET框架中引入的Iterator和Yield功能,但在.NET 4.0中并不支持。需要将其改写为兼容.NET 4.0的代码。

在.NET 4.0中,您可以使用类似迭代器的方式,手动构建一个返回IEnumerable的函数。下面是代码示例:

Private Shared Function AllNodes(ByVal nodes As NodeCollection) As IEnumerable
    Dim nodeList As New List(Of Node)()

    For i As Integer = 0 To nodes.Count - 1
        Dim node As Node = nodes(i)
        nodeList.Add(node)
        If node.Nodes.Count > 0 Then
            For Each item As Node In AllNodes(node.Nodes)
                nodeList.Add(item)
            Next item
        End If
    Next i

    Return nodeList
End Function

以上代码创建了一个List(Of Node),并在遍历过程中手动添加节点,最后返回整个节点列表作为IEnumerable

英文:

Anyone knows about the Iterator equivalent in .net 4.0?

I have a ( Iterator Function / Yield ) code sample which will not compile in my .NET fw 4.0 project.

Need to change it to work in vs.net 2010 .net 4.0, any idea how to proceed?

Thanks.

My sample won't compile in .net 4.0

Private Shared Iterator Function AllNodes(ByVal nodes As NodeCollection) As IEnumerable
	For i As Integer = 0 To nodes.Count - 1
		Dim node As Node = nodes(i)
		Yield node
		If node.Nodes.Count > 0 Then
			For Each item As Node In AllNodes(node.Nodes)
				Yield item
			Next item
		End If
	Next i
End Function

答案1

得分: 2

你至少需要 Visual Basic 11(来自 Visual Studio 2012)的编译器才能构建使用迭代器块的代码。据我所知,.Net 4.0 运行时本身支持这一点,但你需要更新的编译器/构建环境。

但是 Visual Studio 2010 现在非常老旧且完全不受支持。更新的版本是免费的,可以针对旧的运行时环境,所以抓住这个机会进行升级。

英文:

You need the compiler for at least Visual Basic 11 (from Visual Studio 2012) to build code using iterator blocks. IIRC, the .Net 4.0 runtime itself does support this, but you need the newer compiler/build environment.

But Visual Studio 2010 is very old now and completely unsupported. Later versions are free, and can target the older runtime, so take this as a good opportunity to upgrade.

huangapple
  • 本文由 发表于 2023年2月16日 02:22:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75463976.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定