ByVal和ByRef与引用类型

w00*_*977 9 vb.net

请参阅以下代码:

Public Class TypeTest
    Public variable1 As String
End Class

Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim t1 As TypeTest = New TypeTest
        Test(t1)
        MsgBox(t1.variable1)
    End Sub

    Public Sub Test(ByVal t1 As TypeTest)
        t1.Variable1 = "Thursday"
    End Sub

End Class
Run Code Online (Sandbox Code Playgroud)

form_load中的消息框打印:星期四,这意味着对象(TypeTest)通过引用传递.在函数调用中使用ByVal和ByRef作为t1争论有什么区别:Test.

Ste*_*art 17

由于您声明TypeTest为a Class,因此使其成为引用类型(而不是Structure用于声明值类型).引用类型变量充当对象的指针,而值类型变量直接存储对象数据.

您的理解是正确的,ByRef允许您更改参数变量的值,而ByVal不是.当使用值类型之间的差异ByVal,并ByRef很清楚,但是当你使用引用类型使用,该行为是少一点的预期.您可以更改引用类型对象的属性值(即使它被传递ByVal)的原因是因为变量的值是指向对象的指针,而不是对象本身.更改对象的属性根本不会更改变量的值.该变量仍包含指向同一对象的指针.

这可能会让您相信参考类型ByValByRef参考类型之间没有区别,但事实并非如此.它们是有区别的.不同之处在于,当您将reference-type参数传递给ByRef参数时,允许您调用的方法更改原始变量指向的对象.换句话说,该方法不仅能够改变对象的属性,而且还能够将参数变量完全指向另一个对象.例如:

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim t1 As TypeTest = New TypeTest
    t1.Variable1 = "Thursday"
    TestByVal(t1)
    MsgBox(t1.variable1)  ' Displays "Thursday"
    TestByRef(t1)
    MsgBox(t1.variable1)  ' Displays "Friday"
End Sub

Public Sub TestByVal(ByVal t1 As TypeTest)
    t1 = New TypeTest()
    t1.Variable1 = "Friday"
End Sub

Public Sub TestByRef(ByRef t1 As TypeTest)
    t1 = New TypeTest()
    t1.Variable1 = "Friday"
End Sub
Run Code Online (Sandbox Code Playgroud)


dba*_*ett 5

还有更多的例子。一个显示ByRef到ByVal的强制

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
Run Code Online (Sandbox Code Playgroud)