如何将.NET中的列表枚举器作为参数传递给函数?

2026-05-06 08:251阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计430个文字,预计阅读时间需要2分钟。

如何将.NET中的列表枚举器作为参数传递给函数?

观察列表的枚举器传递给函数时,使用byval与byref完全不同。基本而言,常规的byval传递不会改变调用者的enumerator.Current值,即函数内部对枚举器的操作不会影响调用者。而byref则不同,它允许函数直接修改调用者的枚举器状态。

看起来将列表的枚举器传递给函数“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, 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枚举器.

你看到这种行为的原因是List(Of T).Enumerator是一个结构而不是通常所期望的类.因此,当您传递枚举器时,您传递了它的副本,因此当您调用MoveNext时,只会更新该副本

如何将.NET中的列表枚举器作为参数传递给函数?

本文共计430个文字,预计阅读时间需要2分钟。

如何将.NET中的列表枚举器作为参数传递给函数?

观察列表的枚举器传递给函数时,使用byval与byref完全不同。基本而言,常规的byval传递不会改变调用者的enumerator.Current值,即函数内部对枚举器的操作不会影响调用者。而byref则不同,它允许函数直接修改调用者的枚举器状态。

看起来将列表的枚举器传递给函数“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, 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枚举器.

你看到这种行为的原因是List(Of T).Enumerator是一个结构而不是通常所期望的类.因此,当您传递枚举器时,您传递了它的副本,因此当您调用MoveNext时,只会更新该副本

如何将.NET中的列表枚举器作为参数传递给函数?