对我来说有些不清楚的是对 VB.NET 中的类的引用(指针?)。我要问的问题可以通过一些测试来回答,但我想知道是否有人可以发布一个体面的解释(或链接,也是)。
如果你创建一个类:
Public Class ReferenceClass
Private myBooleanValue As Boolean = False
Public Property BooleanValue As Boolean
Get
Return myBooleanValue
End Get
Set(value As Boolean)
myBooleanValue = value
End Set
End Property
End Class
然后是一个实际使用这个类作为属性的类:
Public Class UsingClass
Private myReference As ReferenceClass
Public Property Reference As ReferenceClass
Get
return myReference
End Get
Set(value As ReferenceClass)
myReference = value
End Set
End Property
Public Sub New(ByVal Reference As ReferenceClass)
myReference = Reference
End Sub
End Class
然后像这样使用它:
Public Class RuntimeOrSomething
Public Shared myReference As ReferenceClass
Public Shared ReadOnly Property Reference As ReferenceClass
Get
If myReference Is Nothing Then myReference = new ReferenceClass()
return myReference
End Get
End Property
Public Shared Function BooleanCheck() As Boolean
Reference.BooleanValue = True
Dim tempClass As New UsingClass(Reference)
tempClass.Reference.BooleanValue = False
Return (tempClass.Reference.BooleanValue = Reference.BooleanValue)
End Sub
Public Shared Sub DoNothing()
Reference.BooleanValue = True
Dim someBoolean As Boolean = BooleanCheck
' Now Reference.Booleanvalue is "False"
End Sub
End Class
现在函数BooleanCheck
将始终返回true
,即使引用是UsingClass
“按值”而不是按引用传递给新类的。因此,没有制作类的副本,但myReference
in 中的局部变量UsingClass
仍然引用/指向Reference
.RuntimeOrSomething
这怎么能优雅地解释呢?