Sub / Function array parameter altered

后端 未结 4 1801
一整个雨季
一整个雨季 2021-01-22 19:14

I have a Sub with an array of strings as parameter:

Private Sub des(ByVal array() As String)

    Dim i As Integer

    For i = 0 To UBound(array)
        array(         


        
4条回答
  •  没有蜡笔的小新
    2021-01-22 19:58

    In Visual Basic .NET, regarding arrays as parameters, there are two important rules you have to be aware of:

    Arrays themselves can be passed as ByVal and ByRef.

    Arrays' elements can always be modified from the function or subroutine.

    You already know that you can modify the elements of an array inside a subprocess (subroutine or function), no matter how that array is defined as parameter inside that subprocess.

    So, given these two subroutines:

    Private Sub desval(ByVal array() As String)
        array = {}
    End Sub
    
    Private Sub desref(ByRef array() As String)
        array = {}
    End Sub
    

    And this very simple auxiliary subroutine (here I'll use the Console):

    Private Sub printArr(ByVal array() As String)
        For Each str In array
            Console.WriteLine(str)
        Next
    End Sub
    

    you can do these simple tests:

    Dim arr1() as String = {"abc", "xyz", "asdf"}
    
    Console.WriteLine("Original array:")
    printArr(arr1)
    Console.WriteLine()
    Console.WriteLine("After desval:")
    desval(arr1)
    printArr(arr1)
    Console.WriteLine()
    Console.WriteLine("After desref:")
    desref(arr1)
    printArr(arr1)
    

提交回复
热议问题