【问题标题】:Calling a VB property from its own accessor从自己的访问器调用 VB 属性
【发布时间】:2016-03-16 00:25:32
【问题描述】:

当您从其访问器中访问属性名称时,我正在尝试查找有关 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

【问题讨论】:

  • IDE 应该警告您 MyMinions 在分配值之前已被使用
  • 澄清一下,这是我发现的一个错误,我不想让这段代码工作,我想更好地理解行为
  • getter 就像一个函数,在 VB 中你可以将返回值分配给函数名。因此,它就像一个类型化的占位符变量,因此MyMinions 在(准)函数的开头总是什么都不是,直到你给它赋值。
  • 就像 plutonix 说的那样。在这种情况下,MyMinions 就像一个隐藏变量。改用“Me.MyMinions”。
  • 3. 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 语言规范的 10.1.1.3

标签: vb.net properties


【解决方案1】:

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

一个特殊的局部变量,它在 Get 中隐式声明 访问器主体的声明空间与属性同名, 表示属性的返回值...

规范包括以下示例:

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. 在函数的情况下,隐式局部变量也是 初始化调用函数返回变量,其名称为 函数的名称,其类型是函数的返回类型,并且 其初始值为其类型的默认值。

行为可能在某些时候出现分歧。

【讨论】:

    猜你喜欢
    • 2012-06-08
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多