Static (成员)
 
声明静态成员过程或变量

语法

Type typename
Static variablename As DataType [, ...]
Declare Static Sub|Function procedurename ...
...
End Type

Dim typename.variablename As DataType [= initializer ] [, ...]

[Static] Sub|Function typename .procedurename ...
...
End Sub|Function

说明


  • 静态成员程序
Static??方法没有传递给它们的隐式This实例参数。这允许它们像普通的非成员过程(例如使用回调过程指针)一样使用,唯一的区别在于它们被封装在typename 命名空间中,并且可以访问typename Private或{989796264 }成员。

Static方法可以直接在代码中的任何地方调用,如正常的非成员过程,或类型为typename 的对象,类似于非静态方法,不管任何一种方式都不存在隐式或显式ThisBase)可以在静态方法内进行访问。

对于其原型中的Static的成员程序,也可以在相应的过程体上指定Static,以提高代码可读性。
  • 静态成员变量
Static成员变量仅创建和初始化一次,与任何对象构造无关,与为每个单独对象一次又一次创建的非静态成员变量相反。它们始终为Shared,即使声明中未指定Shared.因此,Static成员变量与全局变量类似,只不过它们在类型命名空间中被声明。

在Type中声明的每个Static成员变量必须通过使用Dim语句在类型外部显式赋值。Type中的声明是每个看到Type声明的模块都可以看到的原型。类型之外的定义赋值并可选地初始化Static成员变量。每个Static成员变量只能有一个定义:它只能在单个模块中赋值,而不能赋值在多个模块中。这与Extern变量相同。

一个Static成员变量受到成员访问控制的约束,除了它在类型之外的定义。如果私有Static成员变量要在Type的成员过程之外显式初始化,则必须为初始化器提供定义。

例子

''显示如何在运行时设置成员调用的实际过程的示例。
''使用静态成员程序。
Type _Object

  Enum handlertype
    ht_default
    ht_A
    ht_B
  End Enum

  Declare Constructor( ByVal ht As handlertype = ht_default)

  Declare Sub handler()

Private:
  Declare Static Sub handler_default( ByRef obj As _Object )
  Declare Static Sub handler_A( ByRef obj As _Object )
  Declare Static Sub handler_B( ByRef obj As _Object )
  handler_func As Sub( ByRef obj As _Object )

End Type

Constructor _Object( ByVal ht As handlertype )
  Select Case ht
  Case ht_A
    handler_func = @_Object.handler_A
  Case ht_B
    handler_func = @_Object.handler_B
  Case Else
    handler_func = @_Object.handler_default
  End Select
End Constructor

Sub _Object.handler()
  handler_func(This)
End Sub

Sub _Object.handler_default( ByRef obj As _Object )
  Print "使用默认方式处理"
End Sub

Sub _Object.handler_A( ByRef obj As _Object )
  Print "使用方法A处理"
End Sub

Sub _Object.handler_B( ByRef obj As _Object )
  Print "使用方法B处理"
End Sub

Dim objects(1 To 4) As _Object => _
  { _
    _Object.handlertype.ht_B, _
    _Object.handlertype.ht_default, _
    _Object.handlertype.ht_A _
  }
  ''第四个数组项将为_Object.handlertype.ht_default

For i As Integer = 1 To 4
  Print i,
  objects(i).handler()
Next i


''为每个类型的实例赋值一个唯一的ID(按创建顺序递增的ID)

Type UDT
  Public:
    Declare Property getID () As Integer
    Declare Constructor ()
  Private:
    Dim As Integer ID
    Static As Integer countID
End Type
Dim As Integer UDT.countID = 0

Property UDT.getID () As Integer
  Property = This.ID
End Property

Constructor UDT ()
  This.ID = UDT.countID
  UDT.countID += 1
End Constructor


Dim As UDT uFirst
Dim As UDT uSecond
Dim As UDT uThird

Print uFirst.getID
Print uSecond.getID
Print uThird.getID


与QB差别

  • 新的FreeBASIC

参考