对我来说有些不清楚的是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
中UsingClass
还引用/指向特性Reference
中RuntimeOrSomething
.
如何优雅地解释这个?
引用指向对象的实例,它不是对象的实例.复制到对象的方向不会创建另一个对象,它会创建另一个也指向同一对象的引用.
我现在不能花很多时间在这个答案上 - 在我膝盖上蹒跚学步的火车上打字 - 但我有几篇文章可能有所帮助.它们是关于C#的,但同样适用于VB.NET:
引用类型和值类型
参数在.NET中传递