.net – 将列表的枚举器传递给函数
发布时间:2020-12-17 07:22:18 所属栏目:百科 来源:网络整理
导读:看起来将列表的枚举器传递给函数“byval”与传递“byref”完全不同.基本上,常规的“byval”传递不会改变调用者的“enumerator.Current值”,即使该函数使枚举器前进.我想知道是否有人知道为什么会这样?枚举器是一个整数的原语,没有对象引用,因此对它的更改不
看起来将列表的枚举器传递给函数“byval”与传递“byref”完全不同.基本上,常规的“byval”传递不会改变调用者的“enumerator.Current值”,即使该函数使枚举器前进.我想知道是否有人知道为什么会这样?枚举器是一个整数的原语,没有对象引用,因此对它的更改不会反映在调用者中吗?
以下是示例代码: 这个函数是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,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枚举器. 解决方法
你看到这种行为的原因是List(Of T).Enumerator是一个结构而不是通常所期望的类.因此,当您传递枚举器时,您传递了它的副本,因此当您调用MoveNext时,只会更新该副本
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |