gpt4 book ai didi

.net - VB.NET 中的引用资料

转载 作者:行者123 更新时间:2023-12-03 07:29:07 26 4
gpt4 key购买 nike

我有点不清楚的是 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,而不是引用。因此,不会创建类的副本,但 UsingClass 中的局部变量 myReference 仍然引用/指向 中的属性 Reference RuntimeOrSomething.

如何优雅地解释这一点?

最佳答案

引用指向对象的实例,但它不是对象的实例。复制该对象的方向不会创建另一个对象,而是创建另一个也指向同一对象的引用。

关于.net - VB.NET 中的引用资料,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/389426/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com