A type
declaration specifies an identifier that denotes a type. The syntax for a type
declaration is
type newTypeName = type
where newTypeName is a valid
identifier. For example, given the type declaration
type
TMyString = string;
you can make the variable declaration
var
S: TMyString;
A type
identifier’s scope doesn’t include the type declaration itself (except for
pointer types). So you cannot, for example, define a record type that uses
itself recursively.
When you
declare a type that is identical to an existing type, the compiler treats the
new type identifier as an alias for the old one. Thus, given the declarations
type
TValue = Real;
var
X: Real;
Y: TValue;
X and Y are of the same type; at runtime,
there is no way to distinguish TValue from Real. This is usually
of little consequence, but if your purpose in defining a new type is to utilize
runtime type information, for example, to associate a property editor with
properties of a particular type, the distinction between different name and
different type becomes important. In this case, use the syntax
type newTypeName
= type type
For
example,
type
TValue = type Real;
forces the compiler to create a new, distinct type called TValue.
Data types and variables: Overview
Type compatibility and identity: Overview
类型声明就是对表示类型的标识符的说明。类型声明的语法是
type newTypeName = type
这里的newTypeName是一个有效标识符。例如,对于给出的如下类型声明
type
TMyString = string;
可以完成如下变量声明
var
S: TMyString;
类型标识符的作用域包括类型声明自身(指针类型除外)。因此,不能定义递归使用自身的类型,如记录类型。
声明一个与存在的类型等同的类型时,编译器将把新的类型标识符视为旧类型的别名。因此,对于给出的如下类型声明
type
TValue = Real;
var
X: Real;
Y: TValue;
这里的X和Y具有相同的类型;运行时,无法区别TValue和Real。这通常没有什么作用,而如果打算在新类型的定义中利用运行时信息,例如,将一个属性编辑器与特别的类型相关联,那么在两个不同名字和不同类型之间有所区别是重要的。这时,可以使用如下语法
type newTypeName
= type type
例如,
type
TValue = type Real;
这里,强制编译器创建了一个叫做TValue的新的、不同于Real类型的类型。