gpt4 book ai didi

vb.net - 从 VB 属性自己的访问器调用它

转载 作者:行者123 更新时间:2023-12-02 09:33:09 25 4
gpt4 key购买 nike

当您从访问器中访问属性名称时,我正在尝试查找有关 VB 属性行为的文档。我预计在 Get the MyMinions 属性访问的第一行中是递归的(ish),但事实并非如此。其访问器内 MyMinions 的值始终为 Nothing,为什么它始终为空,并且在任何地方都有记录?

Public Class MyJob

Public Sub New()
MinionCount = 3
End Sub

Public Property MinionCount As Int32

Public Property MyMinions As List(Of Object)
Get
If MinionCount > 0 AndAlso MyMinions Is Nothing Then
_myMinions = New List(Of Object)() 'here would be DAL call
End If
Return _myMinions
End Get
Set(value As List(Of Object))
_myMinions = value
End Set
End Property
Private _myMinions As List(Of Object) = Nothing

End Class

最佳答案

属性 getter 的行为很像函数,其中名称是隐式的、类型化的局部变量。从 VB 规范 9.7.1 开始:

A special local variable, which is implicitly declared in the Get accessor body's declaration space with the same name as the property, represents the return value of the property...

该规范包括以下示例:

ReadOnly Property F(i As Integer) As Integer
Get
If i = 0 Then
F = 1 ' Sets the return value.
Else
F = F(i - 1) ' Recursive call.
End If
End Get
End Property

代码使用 F = 1 为返回值的局部变量/函数名称赋值,而不是使用 Return 1

因此,在您的代码中,MyMinions 是本地返回变量,并且将是 Nothing(列表的默认值),直到您为其分配某些内容。由于它是一个本地变量,因此不会导致递归。

<小时/>

prop getter 的工作方式与函数非常相似,因此那里的解释 (10.1.1) 也可能会有所帮助:

  1. In the case of a Function, an implicit local variable is also initialized called the function return variable whose name is the function’s name, whose type is the return type of the function and whose initial value is the default of its type.

行为在某些时候可能会有所不同。

关于vb.net - 从 VB 属性自己的访问器调用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36014876/

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