Argument passed ByVal to VB.NET Function and manipulated there

前端 未结 2 815
花落未央
花落未央 2021-01-24 02:21

In this Microsoft sample an array Of Doubles is passed to the functions MultiplyMatricesSequential(...) and MultiplyMatricesParallel(...) as argument r

2条回答
  •  迷失自我
    2021-01-24 03:05

    The distinction is between "value types" and "reference types". Value types are defined as "Structure" (VB.NET) or "Struct" (C#) whereas reference types are defined as "Class". Primitive types such as integer, double and boolean are value types. Arrays are reference types. As @Mattias Åslund pointed out, whether passed ByVal or ByRef, with reference types you are always passing a pointer.

    If you did want to manipulate the passed array but return the original array to the calling procedure, you would need to make a copy into a new locally declared array. Beware of the overhead, however, if passing very large arrays.

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim myOriginalArray As String() = New String() {"Hello", "to", "you", "Michael"}
        ManipulateArray(myOriginalArray)
        MessageBox.Show("myOriginalArray = " & myOriginalArray(0) & " " & myOriginalArray(1) & " " & myOriginalArray(2) & " " & myOriginalArray(3))
    End Sub
    
    Private Sub ManipulateArray(ByVal myOriginalArray As String())
        Dim myCopyArray(myOriginalArray.GetUpperBound(0)) As String
        myOriginalArray.CopyTo(myCopyArray, 0)
        myCopyArray(3) = "Sarah"
        MessageBox.Show("myCopyArray = " & myCopyArray(0) & " " & myCopyArray(1) & " " & myCopyArray(2) & " " & myCopyArray(3))
    End Sub
    

提交回复
热议问题