【问题标题】:Does it matter if the object of List(T) is being passed ByVal or ByRefList(T) 的对象是否通过 ByVal 或 ByRef
【发布时间】:2013-11-13 12:17:54
【问题描述】:

在下面的示例中,是否在函数 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

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    在您的示例中,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。您传递的对象可以被修改(从某种意义上说,您可以调用它的方法和属性设置器来改变它的状态)。但它不能被其他对象替换。

    【讨论】:

    • ListReplacedByVal 有意义:)
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-05
      • 2015-02-15
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      相关资源
      最近更新 更多