ByVal and ByRef with reference type

前端 未结 3 1311
一个人的身影
一个人的身影 2020-12-02 02:04

Please see the code below:

Public Class TypeTest
    Public variable1 As String
End Class

Public Class Form1

    Private Sub Form1_Load(ByVal sender As Obj         


        
3条回答
  •  臣服心动
    2020-12-02 02:34

    A few more examples. One shows ByRef to ByVal forced

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim tt As TypeTest = New TypeTest
        tt.variable1 = "FooBar"
        Debug.WriteLine("'1 " & tt.variable1)
    
        TestByVal1(tt)
        Debug.WriteLine("'2.1 " & tt.variable1)
    
        tt.variable1 = "FooBar"
        TestByVal2(tt)
        Debug.WriteLine("'2.2 " & tt.variable1)
    
        tt.variable1 = "FooBar"
        TestByRef(tt)
        Debug.WriteLine("'3 " & tt.variable1)
    
        tt.variable1 = "FooBar"
        TestByRef((tt)) 'note inner set of () force ref to val
        Debug.WriteLine("'4 " & tt.variable1)
    
        'debug output
        '1 FooBar
        '2.1 FooBar
        '2.2 Monday
        '3 Friday
        '4 FooBar
    End Sub
    
    Public Sub TestByVal1(ByVal t1 As TypeTest)
        t1 = New TypeTest()
        t1.variable1 = "Monday"
    End Sub
    
    Public Sub TestByVal2(ByVal t1 As TypeTest)
        t1.variable1 = "Monday"
    End Sub
    
    Public Sub TestByRef(ByRef t1 As TypeTest)
        t1 = New TypeTest()
        t1.Variable1 = "Friday"
    End Sub
    

提交回复
热议问题