vb.net – 带引用类型的ByVal和ByRef
发布时间:2020-12-17 00:06:47 所属栏目:大数据 来源:网络整理
导读:请参阅以下代码: Public Class TypeTest Public variable1 As StringEnd ClassPublic 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.va
请参阅以下代码:
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 form_load中的消息框打印:星期四,这意味着对象(TypeTest)通过引用传递.
由于您将TypeTest声明为Class,因此它使其成为引用类型(与用于声明值类型的Structure相反).引用类型变量充当对象的指针,而值类型变量直接存储对象数据.
您的理解是正确的,ByRef允许您更改参数变量的值,而ByVal则不允许.使用值类型时,ByVal和ByRef之间的差异非常明显,但是当您使用引用类型时,行为的预期会少一些.您可以更改引用类型对象的属性值的原因,即使它是通过ByVal,也是因为变量的值是指向对象的指针,而不是对象本身.更改对象的属性根本不会更改变量的值.该变量仍包含指向同一对象的指针. 这可能会让您相信参考类型的ByVal和ByRef之间没有区别,但事实并非如此.它们是有区别的.不同之处在于,当您将引用类型参数传递给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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |