Get 语句

Get声明用于检索属性值的属性过程。

语法

[ <attributelist> ] [ accessmodifier ] Get()  
    [ statements ]  
End Get  

部件

术语 定义
attributelist 可选。 请参阅 属性列表
accessmodifier 对于此属性中最多一个 GetSet 语句,可选。 可以是以下值之一:

- 保护
- 朋友
- 私人
- Protected Friend

请参阅 Visual Basic 中的 Access 级别
statements 可选。 调用属性过程时 Get 运行的一个或多个语句。
End Get 必填。 终止属性过程的定义 Get

注解

除非属性被标记WriteOnly,否则每个属性都必须有一个Get属性过程。 该过程 Get 用于返回属性的当前值。

当表达式请求属性的值时,Visual Basic 会自动调用属性 Get 的过程。

属性声明的正文只能包含 Property 语句End Property语句之间的属性GetSet过程。 它不能存储除这些过程以外的任何内容。 具体而言,它无法存储属性的当前值。 必须将此值存储在属性外部,因为如果将该值存储在任一属性过程中,则其他属性过程无法访问它。 通常的方法是在与属性相同的级别声明的 Private 变量中存储值。 必须定义 Get 它所应用到的属性内的过程。

该过程 Get 默认为其包含属性的访问级别,除非 accessmodifier 在语句中使用 Get

规则

  • 混合访问级别。 如果要定义读写属性,可以选择为 GetSet 过程指定不同的访问级别,但不能同时指定两者。 如果执行此作,过程访问级别必须比属性的访问级别更严格。 例如,如果声明Friend属性,则可以声明过程Private,但不能Public声明Get过程。

    如果要定义属性 ReadOnly ,该过程 Get 表示整个属性。 不能声明不同的访问级别 Get,因为这将为属性设置两个访问级别。

  • 返回类型。 Property 语句可以声明它返回的值的数据类型。 该过程 Get 会自动返回该数据类型。 可以指定任何数据类型或枚举、结构、类或接口的名称。

    Property如果未指定returntype语句,该过程将Object返回。

行为

  • 从过程返回。 Get当过程返回到调用代码时,执行将继续在请求属性值的语句中执行。

    Get 属性过程可以使用 Return 语句 或向属性名称分配返回值来返回值。 有关详细信息,请参阅 函数语句中的“返回值”。

    Exit PropertyReturn语句导致立即退出属性过程。 任意数量的 Exit Property 语句 Return 都可以出现在过程中的任意位置,并且可以混合 Exit PropertyReturn 语句。

  • 返回值。 若要从 Get 过程返回值,可以将该值赋给属性名称,或将其包含在 Return 语句中。 该 Return 语句同时分配 Get 过程返回值并退出过程。

    如果不 Exit Property 将值分配给属性名称,该过程 Get 将返回属性数据类型的默认值。 有关详细信息,请参阅 函数语句中的“返回值”。

    下面的示例演示了只读属性 quoteForTheDay 可以返回私有变量 quoteValue中保留的值的两种方式。

    Private quoteValue As String = "No quote assigned yet."
    
    ReadOnly Property QuoteForTheDay() As String
        Get
            QuoteForTheDay = quoteValue
            Exit Property
        End Get
    End Property
    
    ReadOnly Property QuoteForTheDay() As String
        Get
            Return quoteValue
        End Get
    End Property
    

示例:

以下示例使用 Get 语句返回属性的值。

Class propClass
    ' Define a private local variable to store the property value.
    Private currentTime As String
    ' Define the read-only property.
    Public ReadOnly Property DateAndTime() As String
        Get
            ' The Get procedure is called automatically when the
            ' value of the property is retrieved.
            currentTime = CStr(Now)
            ' Return the date and time As a string.
            Return currentTime
        End Get
    End Property
End Class

另请参阅