4

在以下示例中,是否在函数 ByRef 或 ByVal 中都传递 List(T) 对象是否重要?

这是正确的,因为 List 是一个引用类型,所以即使我通过对象 ByVal,值也总是会发生变化。

如果我在更新列表时通过函数“ListChanged”中的对象 byRef 会更好。

Public Class MyClass_

    Public Sub TestMethod()

        Dim List_1 As New List(Of Integer)()
        Dim List_2 As New List(Of Integer)()

        List_1.Add(100)
        List_2.Add(50)

        List_1 = ActualListNotChanged(List_1)  '---101
        List_2 = ListChanged(List_2)        '---50,51

    End Sub


    Private Function ActualListNotChanged(ByVal lst As List(Of Integer)) As List(Of Integer)

        Dim nList As New List(Of Integer)()

        For Each item As Integer In lst
            If item <> 50 Then
                nList.Add(101)
            End If
        Next item

        Return nList

    End Function

    Private Function ListChanged(ByVal lst As List(Of Integer)) As List(Of Integer)

        lst.Add(51)
        Return lst

    End Function

End Class
4

2 回答 2

5

在您的示例中, ByVal (默认值)是最合适的。

ByVal 和 ByRef 都允许您修改列表(例如添加/删除项目)。ByRef 还允许您将列表替换为不同的列表,例如

Dim List1 As New List(Of Int)
List1.Add(1)
ListReplacedByVal(List1)
' List was not replaced.  So the list still contains one item
Debug.Assert(List1.Count = 1) ' Assertion will succeed

ListReplacedByRef(List1)
' List was replaced by an empty list.  
Debug.Assert(List1.Count = 0) ' Assertion will succeed


Private Sub ListReplacedByVal(ByVal lst As List(Of Integer))
    lst = New List(Of Int)
End Sub

Private Sub ListReplacedByRef(ByRef lst As List(Of Integer))
    lst = New List(Of Int)
End Sub

一般来说,您应该使用 ByVal。您传递的对象可以修改(从某种意义上说,您可以调用其方法和属性设置器来更改其状态)。但它不能被不同的对象代替。

于 2013-11-13T12:28:48.087 回答
0

我想说最好的做法是在(且仅当)您要更改列表时使用 ByRef。答案不长,但又短又甜!

于 2013-11-13T12:20:40.113 回答