变量或对象类型的附加名称
概观
宣言
重载分辨率
指向过程指针的指针
输入转发
不完整的类型
概观
类型别名是类型的替代名称。它们可以用于促进从一种类型到另一种类型的质量更改,保存打字或使循环依赖成为可能。
宣言
使用
Type关键字声明类型别名,就像用
外部或
暗淡声明变量或对象。
以下示例声明一个类型别名
Single,称为“
float ”,一个过程,并定义和初始化该类型的两个变量:
Type float As Single
Declare Function add (a As float, b As float) As float
Dim foo As float = 1.23
Dim bar As float = -4.56
过程指针类型别名以相同的方式声明,如以下示例所示:
Declare Function f (ByRef As String) As Integer
Type func_t As Function (ByRef As String) As Integer
Dim func As func_t = @f
Function f (ByRef arg As String) As Integer
Function = CInt(arg)
End Function
重载分辨率
类别别名就是别名。对于所有意图和目的,类别别名
is其别名的类型。因此,就过程重载分辨率而言,使用类型“
alias_to_T ”参数声明的过程与使用类型“
T ”参数声明的过程相同(同样适用于重载成员过程)。
换句话说,这是一个错误重复的定义 - 声明一个过程,其中参数仅在类型和别名中有所不同,如下例所示:
Type float As Single
Declare Sub f Overload (a As Single)
'' If uncommented, this will generate a duplicated definition error
'' Declare Sub f (a As float)
指向过程指针的指针
指向过程指针的指针就像任何其他指针类型一样,除了指向过程指针。因为声明过程指针的语法不允许在过程是函数时直接创建指向过程指针的指针(因为ptr适用于返回类型,而不适用于过程),因此使用类型别名。
以下示例声明一个指向返回整数指针的过程的指针,然后指向指向返回整数的过程的指针:
Dim pf As Function() As Integer Ptr
Type pf_t As Function() As Integer
Dim ppf As pf_t Ptr
输入转发
类型别名可以是前向引用:别名可以引用尚未完全定义的其他类型。
Type foo As bar
Type sometype
f As foo Ptr
End Type
Type bar
st As sometype
a As Integer
End Type
使用类型别名和转发引用允许类型之间的循环依赖关系。
Type list As list_
Type listnode
parent As list Ptr
text As String
End Type
Type list_
first As listnode Ptr
count As Integer
End Type
不完整的类型
一个类型被认为是不完整的,直到它的大小,即在内存中需要占用的字节数是已知的,并且所有字段的偏移是已知的。不可能为不完整的类型赋值空间。不可能声明具有不完整类型的数据类型的变量,将不完整类型作为参数传递,或访问不完整类型的成员。
然而,指向不完整类型的指针可以被赋值,在其他类型中被声明为成员,或者作为参数传递给过程,因为指针的大小是已知的。
Type sometype As sometype_
'' Not allowed since size of sometype is unknown
'' TYPE incomplete
'' a AS sometype
'' END TYPE
'' Allowed since size of a pointer is known
Type complete
a As sometype Ptr
End Type
Dim x As complete
'' Not allowed since size of sometype is still unknown
'' DIM size_sometype AS INTEGER = SIZEOF( sometype )
'' Complete the type
Type sometype_
value As Integer
End Type
'' Allowed since the types are now completed
Dim size_sometype As Integer = SizeOf( sometype )
Type completed
a As sometype
End Type
Dim size_completed As Integer = SizeOf( completed )