References in VB.NET

后端 未结 6 1941
無奈伤痛
無奈伤痛 2021-01-06 19:05

Somewhat unclear to me are references (pointers?) to classes in VB.NET. The question I am about to ask can be answered by a little bit of testing, but I was wondering if any

6条回答
  •  青春惊慌失措
    2021-01-06 19:34

    When passing classes byval/byref in VB.NET it is possible to think of it in terms of C programming and pointers such that -

    ByVal = passing arguments via - a pointer 
    ByRef = passing arguments via - a pointer to a pointer
    

    Take strings as an example

    ' ByRef - modify str pointer to "point" to a new string
    Sub Test_Ref(ByRef str as string)
        str = "New String ByRef"
    End Sub
    
    ' ByVal - can't modify str pointer must return a (pointer to) new string
    Function Test_Val(ByVal str as String) as String
        Return "New String ByVal"
    End Sub
    
    Sub Main()
        Dim strTest as String = "Hello World!"
        Console.WriteLine(strTest)
        Test_Ref(strTest)
        Console.WriteLine(strTest)
        Test_Val(strTest)
        Console.WriteLine(strTest) ' oops still pointing to same string
        strTest = Test_Val(strTest)
        Console.WriteLine(strTest) ' that's better :)
    End Sub
    

提交回复
热议问题