微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

.net – 将列表的枚举器传递给函数

看起来将列表的枚举器传递给函数“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时,只会更新该副本

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐