看起来将列表的枚举器传递给函数“byval”与传递它的“byref”完全不同。本质上,常规的“byval”传递不会改变调用者的“enumerator.Current value”,即使函数推进了枚举器。我想知道是否有人知道为什么会这样?枚举器是不是像整数一样的原语,没有对象引用,因此对它的更改不会反映在调用者中?
这是示例代码:
这个函数是 byval,并陷入无限循环,吐出“1”消息框,因为枚举器的“当前”永远不会超过 5:
Public Sub listItemsUsingByValFunction()
Dim list As New List(Of Integer)(New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
Dim enumerator = list.GetEnumerator()
enumerator.MoveNext()
While enumerator.Current <= 5
listFirstItemByVal(enumerator)
End While
End Sub
Private Sub listFirstItemByVal(ByVal enumerator As List(Of Integer).Enumerator)
MsgBox(enumerator.Current)
enumerator.MoveNext()
End Sub
另一方面,这正如人们所期望的那样工作:
Public Sub listItemsUsingByRefFunction()
Dim list As New List(Of Integer)(New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
Dim enumerator = list.GetEnumerator()
enumerator.MoveNext()
While enumerator.Current <= 5
listFirstItemByRef(enumerator)
End While
End Sub
Private Sub listFirstItemByRef(ByRef enumerator As List(Of Integer).Enumerator)
MsgBox(enumerator.Current)
enumerator.MoveNext()
End Sub
两个函数之间的区别仅在于 listFirstItem__ 函数是接受 byval 还是 byref 枚举器。