Difference between ByVal and ByRef?

后端 未结 9 2315
囚心锁ツ
囚心锁ツ 2020-12-15 19:34

What is the difference? I always use ByVal, but, I don\'t really have a good idea of when should I and when not...

9条回答
  •  感动是毒
    2020-12-15 20:00

    I know this question has pretty much been answered, but I just wanted to add the following...

    The object you pass to a function is subject to ByRef/ByVal, however, if that object contains references to other objects, they can be modified by the called method regardless of ByRef/ByVal. Poor explanation, I know, see code below for a better understanding:

    Public Sub Test()
        Dim testCase As List(Of String) = GetNewList()
        ByRefChange1(testCase)
        'testCase = Nothing
        testCase = GetNewList()
    
        ByValChange1(testCase)
        'testCase is unchanged
        testCase = GetNewList()
    
        ByRefChange2(testCase)
        'testCase contains the element "ByRef Change 2"
        testCase = GetNewList()
    
        ByValChange2(testCase)
        'testCase contains the element "ByVal Change 2"
    
    End Sub
    
    Public Function GetNewList() As List(Of String)
        Dim result As List(Of String) = New List(Of String)
        result.Add("Value A")
        result.Add("Value B")
        result.Add("Value C")
        Return result
    End Function
    
    Public Sub ByRefChange1(ByRef aList As List(Of String))
        aList = Nothing
    End Sub
    
    Public Sub ByValChange1(ByVal aList As List(Of String))
        aList = Nothing
    End Sub
    
    Public Sub ByRefChange2(ByRef aList As List(Of String))
        aList.Add("ByRef Change 2")
    End Sub
    
    Public Sub ByValChange2(ByVal aList As List(Of String))
        aList.Add("ByVal Change 2")
    End Sub
    

    EDIT:

    Also, consider if this function was called:

    Public Sub ByValChange3(ByVal aList As List(Of String))
        aList.Add("ByVal Change 3")
        aList = New List(Of String)
        aList.Add("ByVal Change 4")
    End Sub
    

    What happens in this case is "ByVal Change 3" is added to the callers list, but at the point you specify that "aList = New List" you are then pointing the new reference, to a new object, and become detached from the callers list. Both common sense and might catch you out one day, so something to bear in mind.

提交回复
热议问题